PHP detailed and thorough learning Smarty_PHP tutorial

Source: Internet
Author: User
Tags split words
PHP thoroughly learns about Smarty. All the smarty labels in the basic syntax are added with delimiters. in smarty, all contents other than delimiters are static. When smarty encounters a template tag, it will try to explain them and then use the basic syntax
All smarty labels are added with delimiters. in smarty, all contents other than delimiters are static. When smarty encounters a template tag, it will try to explain them and then output them in an appropriate way.

By default, they are {and}, but they are customizable. the custom method is:
$ Smarty-> left_delimiter =' ';

1. Notes

Template comments are surrounded by "*", for example, {* this is a comment *}
The smarty annotation will not be output. it is an internal annotation of the template.

2. variables
The template variable starts with $ and can contain numbers, letters, and underscores.
The config_file variable is an exception and must be referenced using the # variable name # method.

3. Functions
The smarty tag outputs a variable or calls a function.
Functions and their attributes in the delimiters will be processed and output. for example:
{Funcname attr1 = "val" attr2 = "val "}.
Funcname indicates the function name, such as include, attr1, attr2 indicates the attribute name, and val indicates the value corresponding to the attribute.

Both built-in and custom functions have the same syntax in the template.
Built-in functions will work within smarty, such as {if}, {section}, and {strip}. they cannot be modified.
UDFs work through the plug-in mechanism. they are additional functions and can be modified at will.
For example, {html_options} and {html_select_date}

4. attributes
Static values do not require quotation marks, and Boolean values (true or false) do not require quotation marks. they can be true, on, yes, false, off, or no. except string. variables are also used, and they cannot be enclosed in quotation marks.

5. Insert a variable into the string
Only a combination of numbers, letters, underscores, and [] can be recognized. for complex forms, use ''to separate variables. For example, {func var = "test $ foo. the variable $ foo can only be identified in bar test "}, and $ foo must be recognized. bar, which must be written as {func var = "Test' $ foo. bar 'test "} format.

6. display methods of reserved words
In the template, if you want to display some reserved words of smarty as the content of the language, such as the Display separator, the default method is {}: {ldelim }, {rdelim} or {$ smarty. ldelim}, {$ smarty. rdelim} or put {} in {literal }.. {/literal} intermediate output.

Retention variable of smarty

{$ Smarty} reserved variables can be used to access some special template variables.
The following are all.

Page request variable
The following are examples of access page request variables such as get, post, cookies, server, enviroment, and session variables. for example, {$ smarty. server. SERVER_NAME} gets the server variable, {$ smarty. env. PATH} obtains the path of the system environment variable {$ smarty. request. username} obtains the compound variable of get/post/cookies/server/env.

The variable {$ smarty. now} is used to access the current timestamp.
You can use the date_format regulator to format the output. for example, {$ smarty. now | date_format: "% Y-% m-% d % H: % M: % S "}

{$ Smarty. const}
You can directly access PHP constants. for example, {$ smarty. const. _ MY_CONST_VAL}

{$ Smarty. capture}
You can use the {$ smarty} variable to access the output captured by the {capture}... {/capture} structure.

{$ Smarty. config}
The variable {$ smarty} can access the loaded config variable.
For example, {$ smarty. config. foo} indicates {# foo #}.

{$ Smarty. section}, {$ smarty. foreach}
The {$ smarty} variable can be used to access the attributes of the 'core' and 'foreach' loops.

{$ Smarty. template}
Displays the name of the currently processed template.

{$ Smarty. version}
Display the version of the smarty Template

{$ Smarty. ldelim}
Show left separator

{$ Smarty. rdelim}
Show right separator

Variable regulator
The variable regulator is used for variables, user-defined functions, and strings.
You can use the '|' symbol and the regulator name to apply the regulator.
The behavior of a variable regulator is determined by the value of the parameter.
Parameters are separated by the ':' symbol.
If you use the variable regulator to adjust the array variables, the result is that each value of the array is adjusted. if you want the regulator to adjust the entire array, you must add the @ symbol before the regulator name.
Example: {$ articleTitle | @ count} (this will be the number in the output $ articleTitle array)

Capitalize
Capital the first word of all words in the variable. the parameter value is boolean to determine whether a word with a number is capitalized. Not capitalized by default

Count_characters
Calculates the number of characters in the variable value. The parameter value boolean determines whether to calculate the number of spaces. Space is not calculated by default.

Cat
Connect the parameter values in cat to the specified variable. the default value is null.

Count_paragraphs
Calculates the number of paragraphs in a variable.

Count_sentences
Calculates the number of sentences in a variable.

Count_words
Calculate the number of words in a variable

Date_format
Date format

The first parameter controls the date format.
If the data passed to date_format is empty, the second parameter is used as the default time.

% A-the day of the week

% A-full writing of the day of the week

% B-abbreviated month

% B-full write of the month

% C-date and time 06/12/05 11:15:10

% C-century time

% D-number of the month (from 01 to 31)

% D-same as % m/% d/% y

% E-the number of months. if it is a singular number, add a space (from 1 to 31) to the front)

% G-century

% G-century [century, 9999]

% H-same as % B

% H-24 hours (from 00 to 23)

% I-12 hours (from 01 to 12)

% J-the day of the year (from 001 to 366)

% K-24 hours, with a space in front of a single number (from 0 to 23)

% L-12 hours, with a space in front of a single number. (range 1 to 12)

% M-month (range 01 to 12)

% M-minute

% N-linefeed

% P-display 'am' or 'PM 'in the morning or afternoon'

% R-a.m. or p. m. Format time

% R-24 hour time

% S-second

% T-tab

% T-same as % H: % M: % S

% U-[] indicates the day of the week

% U-computing is the week of the year. it starts from the first Sunday of the year.

% V-calculate the week of the year, from 01 to 53. the first week must have at least four days in the year, and Sunday is the first day of the week.

% W-represents the day of the week in the form of a number, and Sunday is 0

% W-the week of the year in the form of digits, starting from the first Monday of the year

% X-Display date: month/day/year

% X-display Time: Hour: minute: Second

% Y-not including the year of the century

% Y-Year of the century

% Z-time zone

%-Output %

Some of them sometimes cannot be output normally.

Default
Default
Set a default value for null variables.
When the variable is null or unallocated, the output is replaced by the given default value.

Escape
Transcoding
The parameter values are html, htmlall, url, quotes, hex, hexentity, and Cr limit pt. The default format is html transcoding.

Indent
Indent
In each line of the indent string, the first parameter specifies the number of characters to indent. the default value is 4 characters. The second parameter specifies the characters used to indent the string.

Lower
Lowercase
This is used to lowercase a variable.
Lowercase variable string

Nl2br
Replace line breaks


Regex_replace
Regular expression replacement
Find and replace a regular expression. there must be two parameters. parameter 1 is to replace a regular expression. parameter 2 is to replace a text string.

Replace
Replace
A simple search and replacement string must have two parameters. parameter 1 is the string to be replaced, and parameter 2 is the text to be replaced.

Spacify
Spacify inserts spaces or other strings between each character of a string. the parameter indicates the string to be inserted between two characters. the default value is a space.

String_format string formatting
It is a method for formatting floating-point numbers, such as decimal numbers. it is formatted using the sprintf syntax. Parameters are required, and the format is required. % D indicates an integer, and %. 2f indicates two floating point numbers are truncated.

Strip removal (extra space)
Replace all repeated spaces. line feed and tab are single or specified strings. if there is a parameter, it is the specified string.

Strip_tags remove all html tags

Truncate interception
Parameter 1, specifies the number of characters intercepted. the default value is 80.
The second parameter specifies the characters after the intercepted string. the default value is...
The third parameter determines whether to accurately intercept words. if it is false by default, smarty does not split words.

Upper converts the variable to uppercase

Wordwrap row width constraint
The first parameter specifies the width of the paragraph (that is, the number of characters in a row, exceeding the number of characters in line). The default value is 80.
The second parameter specifies the characters used at the constraint point (the default is the line break \ n ).
The third parameter determines whether to accurately intercept characters. by default, the characters cannot be separated during intercept.
Built-in functions
Built-in functions cannot be modified without authorization.
Capture
The capture function is used to collect the data output from the template to a variable instead of outputting the data to the page. for example, any data between {capture name = "foo"} and {/capture} is received in the variable {$ foo} specified by the function name attribute, or {$ smarty. capture. foo. If the function does not have a name attribute, "default" will be used. Each {capture} must correspond to {/capture}, and the capture function cannot be nested.

Config_load
Reference configuration file
File is required. it indicates the name of the configuration file to be included, section indicates the name of the part to be loaded, and scope of the variable to be processed by scope. it must be local, parent, or global.
Local means that the variable will be loaded in this template.
Parent means that the variables will be loaded in this template and the parent template.
Global means that the variable will be applied to all templates. the default value is local. Whether the variable is visible in the upper-level template. the default value is no. If the scope attribute already exists, this value is ignored.

Foreach, foreachelse
A foreach loop is a selective section loop. it is used to traverse associated arrays. the syntax of foreach is much simpler than section, but as a compromise, it can only be used for simple arrays.
The required parameters of foreach are from and item. the from variable indicates the name of the array to be cyclic, the item indicates the variable name of the current element, the key indicates the variable name of the current keyword, and the name indicates the foreach loop name that accesses the foreach attribute. Loops can be nested with each other. the names of nested loops must be independent. foreachelse is executed when the from variable has no value.

Include
Used to reference other templates.
The file attribute is required to indicate the name of the referenced template, and assign indicates the output variable to be allocated to the include file. You can define any local variable by using the property name = "property value.

Include_php
It is used to introduce php scripts in the template. File is required to indicate the path of the php script. once, determine whether to load the php script once if it is referenced multiple times in the template. The default value is true.

Insert
It is used to include the function in the php script. name is required to indicate the name of the inserted script. Note that if the name is name, the included function is insert_name (), therefore, all functions to be inserted must have the prefix insert _. If the assign attribute is used, the insert output will be allocated to the template variables and will not be displayed. Scr limit pt indicates the script path to be referenced. The content produced by this program will not be cached and re-executed each time the page is called. this applies to interaction areas such as advertising, voting, and query results.


If, elseif, else
The if statement is similar to the condition in php, but each word must be separated by a space. There are also some new condition statements, which are listed as follows: equal eq, unequal ne and neq, greater than gt, less than, greater than or equal to gte and ge, less than or equal to lte and le, not Non. mod modulo. Is [not] p by can be divisible by a certain number, is [not] even is an even number, $ a is [not] even by $ B ($ a/$ B) % 2 = 0, is [not] whether odd is odd, $ a is not odd by $ B ($ a/$ B) % 2! = 0

Php
Php markup allows the template to directly use the php language.

Section, sectionelse
Section is used to display array data cyclically. name and loop are required parameters. Name indicates that the nested name. section can be nested, but the names must be different. Loop indicates the number of cycles. sectionelse outputs when the loop parameter is null. Start is used to specify the pointer at the beginning of the loop. if the value is negative, the pointer starting from the end of the array is calculated. the default value is 0. step indicates the number of cycles. if it is negative, it is reversed. the default value is 1. max sets the maximum number of cycles. show determines whether to display section.
Section also has its own variable processing section attribute, which is displayed using {$ smarty. section. sectionname. varname.

Index
Index is used to display the pointer of the current loop, starting from 0.

Index_prev
The pointer used to display the previous loop, starting from-1.

Index_next
The pointer used to display the next loop.

Iteration
Displays the number of times of the current loop, starting from 1.

First
If the current loop is the first loop, the value is true.

Last
If the current loop is the last loop, the value is true.

Rownum
Same as iteration.

Loop
Display the pointer of the last loop, which can be used anywhere in the center of the section or after the section.

Show
Show determines whether to display section.

Total
Displays the total number of cycles, which can be used anywhere in the center of a section or after a section.

Strip
Remove unnecessary spaces
Regular functions
Assign
Assign is used to assign variable value. var when executing the template. value is a required parameter. var is the variable name of the value to be allocated, and value is the allocated value.

Counter
Counter is used to output a count. multiple counts can be used, but the names must be different. name indicates the counter name. The default value is default. start indicates the initial count value. The default value is 1. skip count interval. the default value is 1. direction indicates the counting direction, up or down. The default value is up. print indicates whether to print the value. The default value is true. assign defines the Template variables, and the counter output will be allocated to the variables defined by assign.

Cycle
Cycle is used to show a set of values cyclically. name indicates the cycle name, values ("value 1", "value 2 ",...) A group of values displayed in a loop. print indicates whether to display. advance determines whether to display the next value. delimiter determines the delimiter of value. The default delimiter is comma. assign defines the Template variables. cycle output will be allocated to the variables defined by assign.

Debug
Debug can display all variables with assigned values, but the template content is not displayed. the output attribute determines the display format html or javascr release pt. the default value is html.

Eval
Eval is used to insert variables into variables. Var is the name of the inserted variable. assign assigns the output to a variable.

Fetch
This interface is used to obtain the file content and output the file content. it can obtain local files, http files, and ftp files. file is the path for obtaining files, and assign assigns the output to a variable.

Html_checkboxes
Html_checkbox is used to create a checkbox with the given data. Name indicates the name of the checkbox, values indicates the value of the checkbox, output indicates the display of the checkbox, selected indicates the value of the selected option, and options indicates the value and display of a group of checkboxes, separator indicates the delimiter used to separate each checkbox. labels indicates adding labels to the output. the default value is true.

Html_image
Html_image is used to create an html tag for an image. it is automatically generated if no value is assigned for the height and width values. File is the path of the image, and its height, width, and alt are the same as the html tag. basedir is the path of the directory starting from the relative path of the image. the default path is the server root directory. Href defines the link of the image.

Html_options
Output drop-down list. the parameters include name, values, output, selected, and options.

Html_radios
Output single-digit. the parameters are the same as the check box.

Html_select_date
Prefix defines the prefix of names in each drop-down list. the default value is Date _. Time determines the time to use. the default value is the current time. Start_year determines the year from the drop-down list, which can be expressed by year or the relative number of years from the current year. The default value is the current year. End_year determines the year when the drop-down list ends. it can be expressed by year or the relative number of years from the current year. The default value is the current year. Display_days determines whether to display the date. Display_months determines whether to display the month. Display_years determines whether to display the year. Month_format determines the format of the displayed Month. the default value is % B. Day_format determines the display date format. the default value is % 02d. Day_value_format determines the date value format. the default value is % d. Month_value_format determines the format of the month value. The default value is % m. Year_as_text determines whether to output the year in text format. Reverse_years determines whether to reverse output each year. Field_array is used to obtain a set of variables. values obtained from form can be obtained using name [Day], name [Month], name [Year. Day_size, month_size, and year_size add size labels. All_extra, day_extra, month_extra, and year_extra add additional attributes to the select or input tag. Field_order determines the order of the drop-down list, which is MDY by default. The delimiter between different drop-down lists of field_separator. the default value is \ n. Year_empty, month_empty, and day_empty are displayed in the first column of each drop-down list.

Html_select_time
Prefix defines the prefix of each drop-down list name. The default value is Time _. Time determines the time to use. the default value is the current time. Display_hours determines whether to display the hour. Display_minutes determines whether to display the minute. Display_seconds determines whether to display the seconds. Display_meridian determines whether to display am/pm. Use_24_hours determines whether the 24-hour system is used. Minute_interval determines the interval between minutes. Second_interval determines the interval between seconds. Field_array is used to obtain a set of variables. values obtained from form can be obtained using name [Hour], name [Minute], name [Second. All_extra, hour_extra, minute_extra, second_extra, and meridian_extra add additional attributes to the select or input tag.

Html_table
Loop defines a set of data used for loop. Cols determines the number of columns, and rows determines the number of rows. if one of them is empty and the other has a value, the other value is calculated based on the number of elements and the property with values, the default value is 3. The inner determines the columns of the columns in cols, and the rows in rows are arranged in rows. the default value is cols. Table_attr, tr_attr, and td_attr are table, tr, and td. if tr_attr and td_attr are arrays, tags are added cyclically. Trailpad is used to fill cells with no value in the last row. the default value is. Hdir determines the arrangement direction of elements in each row, from left to right or from right to left. the default value is right. Vdir determines the arrangement direction of each column, from top to bottom down or from bottom to top up. the default value is down.

Math
Perform numeric operations. Equation and var are required. Equation defines the formula. the operators that can be used include +,-,/, *, abs, ceil, cos, exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, srans and tan. Var assigns values to the operation variables. Format determines the format of the result. Assign assigns the output to a parameter.

Mailto
Using the mailto function makes it difficult for a web spider to obtain your email address, but it can be displayed on a webpage as it encrypts the email address. Address is required. it defines the email address. Text is the text content displayed on the page. the default value is the email address. Encode is used to encrypt the email address. it can be none, hex, or javascr encrypted pt. the default value is none. If you want to send emails to other mailboxes, cc can be used for cc. separate email addresses with commas. Bcc is a bcc copy. Subject is the subject of the email. Newsgroups is a news group that publishes content. newsgroups are separated by commas. Add additional tags to extra. Followupto is unknown.

Textformat
Textformat is used to format text. it removes spaces and special characters, and specifies the line width and indentation. Style specifies the current format, and indent specifies the number of digits of indentation. Indent_first specifies the indent of the first line. Indent_char refers to the indentation character, which is a space by default. Wrap specifies the row width, that is, the number of characters in a row. the default value is 80. Wrap_char specifies the delimiter of each line. The default value is \ n. Wrap_cut determines whether to separate words. Assign assigns the output to the variable.
Constant
SMARTY_DIR
Is the full path to the smarty directory, which must end. If not defined, the path is automatically determined.

SMARTY_CORE_DIR
Is the full path to the smarty core file directory, which must end. If not, it is automatically defined as a subdirectory under the smarty_dir path.


Variable

$ Template_dir
The default template directory name. The default value is "./templates ".
$ Compile_dir
The default directory name of the compiled template. the default value is "./templates_c"
$ Config_dir
The default config file directory name. The default value is "./configs ".
$ Plugins_dir
Default plug-in directory name. default value: "plugins ".
$ Debugging
Debugging console. That is, a window showing variables.
$ Debug_tpl
Debug window Template
$ Debugging_ctrl
Another method to control debugging.
$ Autoload_filters
Use a filter program for all templates. this variable is an array, where the keyword is the filter type and the value is the name of the filter.
$ Compile_check
Each php execution checks whether the template content is changed.

$ Caching
Determines whether to cache the file generated by execution.
$ Cache_dir
The default template cache directory name. The default value is "./cache ".
$ Cache_lifetime
The expiration time of the cached template. if the value of $ caching is-1, the cached template will never expire.
Finally, let me give you an example.

Error_reporting (7 );
$ TurnDot = substr (PHP_ OS, 0, 3) = 'win '? ";":":";
$ Doc_root = $ _ SERVER ['document _ root']; // Obtain the ROOT path by default.
// $ Doc_root = "E:/Myweb/an-cool.com/Web"; // The specified path
$ Lib_root = ". ". $ TurnDot. $ doc_root. "/shopadmin ". $ TurnDot. $ doc_root. "/shopadmin/inc ". $ TurnDot. $ doc_root. "/". $ TurnDot. $ doc_root. "/jpgraph/src /". $ TurnDot. $ doc_root. "/Smarty/libs /". $ TurnDot. $ doc_root. "/Smarty ";
Ini_set ("include_path", $ lib_root );
Include ("conf. global. php"); // loads a global configuration file.
$ Templates_root = $ doc_root. "/templates"; // defines the touch version root directory
Define ("Templates", $ Templates_root );
$ Templates = isset ($ INFO ['templates'])? $ INFO ['templates']: 'default ';
Include_once ('smarty. class. php ');
$ Tpl = new Smarty (); // Create a smarty instance object $ tpl
$ Tpl-> debugging = false;
$ Tpl-> template_dir = Templates. "/". $ templates; // set the template directory
Tpl-> compile_dir = Templates. "/". $ templates. "/templates_c"; // Set the compilation Directory
$ Tpl-> cache_dir = $ doc_root. "/cache"; // sets the cache directory.
$ Tpl-> cache_lifetime = 60*60*24; // Set the cache time.
$ Tpl-> cache_lifetime = 0; // you can specify the cache time.
$ Tpl-> caching = false; // set this parameter to false during debugging. use true for release.
$ Tpl-> left_delimiter = '<{';
$ Tpl-> right_delimiter = '}> ';
$ Tpl-> assign ("template_dir", $ INFO ['site _ url']. "/templates/". $ templates); // path
$ Tpl-> assign ("Site_Url", $ INFO ['site _ url']); // The Origin site url
$ Tpl-> assign ("LanguageIs", $ INFO ['is']); // Language Pack type
$ Tpl-> assign ("HtmlTitle", $ INFO ['site _ title']); // title content
$ Tpl-> assign ("HtmlMeta", $ INFO ['meta _ keyword']); // meta content
?>

All the smarty labels of the secret are added with delimiters. in smarty, all contents other than delimiters are static. When smarty encounters a template tag, it will try to explain them, and then start...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.