Basic syntax
All smarty tags are delimited. In smarty, all content other than delimiters are static. When smarty encounters template tags, it will try to interpret them and then use them appropriately.
The default is { and }, but they are customizable. The customization method is:
$smarty->left_delimiter = '';
1. Comments
Template comments are surrounded by * signs, such as {* this is a comment *}
smarty comments will not be output. It is an internal comment of the template.
2. Variables
Template variables start with $ and can contain numbers, letters and underscores.
The config_file variable is an exception and must be referenced using the #variablename# method.
3. Function
The smarty tag outputs a variable or calls a certain function.
The function and other functions within the delimiter Attributes will be processed and output. For example:
{funcname attr1="val" attr2="val"}.
funcname is the name of the function, such as include, etc., attr1 and attr2 are the attribute names, and val is the attribute corresponding value.
Both built-in functions and custom functions in templates have the same syntax.
Built-in functions will work inside smarty, such as {if}, {section} and {strip}. They Cannot be modified.
Custom functions work through the plug-in mechanism. They are additional functions that can be modified and added at will.
For example {html_options} and {html_select_date}
4. Attributes
Static values do not need quotes, and Boolean values (true or false) do not need quotes. They can be true, on, yes or false, off, no. But strings are an exception. Variables are also used, and they cannot be quoted. .
5. Insert variables into the string
can only recognize combinations of numbers, letters, underscores and []. If it is a complex form, you need to separate the variables with ``. For example, {func var="test $foo.bar test"} can only recognize the variable $foo. To recognize $foo.bar, it needs to be written in the format of {func var="test `$foo.bar` test"}.
6. How to display some reserved words
If you want to display some reserved words of smarty as language content in the template, such as displaying delimiters, the default method is {}: {ldelim },{rdelim} or {$smarty.ldelim},{$smarty.rdelim} or you can put {} in the middle of {literal} .. {/literal} to output.
Smarty reserved variables
{$smarty} reserved variables can be used to access some special template variables.
The following are all.
Page request variables
The following are examples of accessing page request variables such as get, post, cookies, server, environment and session variables. For example, {$smarty.server.SERVER_NAME} obtains server variables, {$smarty.env.PATH} obtains system environment variable path , {$smarty.request.username} obtains the composite variable of get/post/cookies/server/env.
{$smarty.now} variable is used to access the current timestamp.
You can use the date_format adjuster to format the output. For example {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
{$smarty.const}
You can access PHP constants directly. For example {$smarty.const._MY_CONST_VAL}
{$smarty .capture}
The output captured through the {capture}..{/capture} structure can be accessed using the {$smarty} variable.
{$smarty.config}
{$smarty} variable Can access loaded config variables.
For example {$smarty.config.foo} can represent {#foo#}.
{$smarty.section}, {$smarty.foreach}
{$smarty} variables can access the properties of 'section' and 'foreach' loops.
{$smarty.template}
Displays the name of the template currently being processed.
{ $smarty.version}
Show smarty template version
{$smarty.ldelim}
Show left delimiter
{$smarty.rdelim}
Show right delimiter Symbols
Variable adjusters
Variable adjusters are used for variables, custom functions and strings.
Adjusters can be applied using the '|' symbol and the adjuster name.
Variable adjusters are used by The value assigned to the parameter determines its behavior.
The parameters are separated by ':' symbols.
If you adjust an array variable with a variable adjuster, the result is that every value of the array is adjusted. If you want the adjuster to adjust For the entire array, you must precede the regulator name with the @ symbol.
For example: {$articleTitle|@count} (this will output the number in the $articleTitle array)
capitalize
Capitalize the first letter of all words in the variable. The parameter value boolean determines whether the first letter of the word with a number is capitalized. Not capitalized by default
count_characters
Count the number of characters in the variable value. The parameter value boolean determines whether to count the number of spaces. By default, spaces are not counted.
cat
Connect the parameter value in cat to the given variable. The default is empty.
count_paragraphs
Count the number of paragraphs in the variable
count_sentences
Count the number of sentences in the variable
count_words
Count the number of words in the variable
date_format
Date format
The first parameter controls the date format.
If the data passed to date_format is empty, the second parameter will be used as the default time
%a - Abbreviation of day of the week
%A - Abbreviation of day of week
%b - Abbreviation of month
%B - Abbreviation of month
%c - date and time 06/12/05 11:15:10
%C - century time
%d - the number of the month (from 01 to 31 )
%D - Same as %m/%d/%y
%e - The number of the month, if the number is an odd number, add a space in front (from 1 to 31)
%g - century
%G - century [0000,9999]
%h - same as %b
%H - hour in 24-hour format (from 00 to 23)
%I - hour in 12-hour format (from 01 to 12)
%j - day of the year (from 001 to 366)
%k - The hour in 24-hour format, with a space before the singular digit. (from 0 to 23)
%l - The hour in 12-hour format, with a space before the singular digit. (range 1 to 12)
%m - Month (range 01 to 12)
%M - Minutes
%n - Line break
%p - Display morning Or afternoon `am' or `pm'
%r - time in the form of a.m. or p.m.
%R - time in 24-hour format
%S - seconds
%t - tab symbol
%T - same as %H:%M:%S
%u - use [1,7] to represent the day of the week
%U - The calculation is the number of weeks of the year, starting from the first Sunday of the year
%V - The calculation is the number of weeks of the year, from 01 to 53, A week must have at least 4 days in this year, Sunday is the first day of the week
%w - represents the day of the week in numerical form, Sunday is 0
%W - The number of weeks in the year in numeric form, starting from the first Monday of the year
%x - Display date: month/day/year
%X - Display time: hour: minute: second
%y - year excluding century
%Y - year including century
%Z - time zone
%% - Output%
Some of them sometimes cannot be output normally.
default
Default
Set a default value for an empty variable.
When the variable is empty or unassigned, the output will be replaced by the given default value.
escape
Transcoding
The parameter values are html, htmlall, url, quotes, hex, hexentity, javascrīpt. The default is html transcoding
indent
Indentation
Indent the string in each line. The first parameter specifies how many characters to indent. The default is 4 characters. The second parameter, Specifies what character to use for indentation.
lower
lowercase
This is used to lowercase a variable.
Lowercase the variable string
nl2br
Replace newline characters with
regex_replace
Regular replacement
Find and replace regular expressions. There must be two parameters. Parameter 1 is the replacement regular expression. Parameter 2 uses what text string to replace
replace
Replace
Simple search and replace strings must have two parameters, parameter 1 is the string to be replaced. Parameter 2 is the text used to replace
spacify
spacify inserts a space or other string between each character of the string. The parameter indicates the string that will be inserted between two characters, and the default is a space.
string_format String formatting
is a method of formatting floating point numbers. For example, decimal numbers. Use sprintf syntax to format. The parameter is required and specifies the formatting method to be used. %d means displaying an integer, %.2f means intercepting two floating point numbers.
strip removes (excess spaces)
Replaces all repeated spaces, newlines and tabs with a single or specified string. If there are parameters, it is the specified string.
strip_tags removes all html tags
truncate interception
Parameter 1 specifies the number of characters to intercept. The default is 80.
The second parameter specifies the intercepted character What characters should be added after the string. The default is...
The third parameter determines whether to intercept accurately. By default, it is false, and smarty will not split words.
upper Change the variable to uppercase
wordwrap line width constraint
The first parameter specifies the width of the paragraph (that is, how many characters per line, if more than this number of characters, wrap). The default is 80 .
The second parameter specifies what character to use at the constraint point (the default is the newline character n).
The third parameter determines whether to intercept characters accurately. By default, it is inexact interception, that is, words cannot be separated during interception. .
Built-in functions
Built-in functions cannot be modified without authorization.
capture
The function of the capture function is to collect the data output by the template into a variable instead of outputting them to the page. For example, any data between {capture name="foo"} and {/capture} are received in the variable {$foo} specified by the function's name attribute, or in {$smarty.capture.foo}. If the function has no name attribute, "default" will be used. Each {capture} must correspond to {/capture}, and capture functions cannot be nested.
config_load
Referring to the configuration file
file is required, indicating the name of the configuration file to be included, section indicating the name of the part to be loaded, and the scope of the variable being processed by scope. Must be local, parent or global.
local means that the variable will be loaded in this template.
parent means that the variable will be loaded in this template and the superior template.
global means that the variable will be applied to all templates. The default is local. Whether the variable is visible in the superior template, the default is no. If the scope attribute already exists, this value will be ignored.
foreach, foreachelse
The foreach loop is a selective section loop. It is used to traverse associative 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 represents the name of the array that needs to be looped, item represents the variable name of the current element, and key represents the variable name of the current keyword. , name represents the name of the foreach loop that accesses the foreach attribute. Loops can be nested into each other, and the names between nested loops must be independent. foreachelse is executed when the from variable has no value.
include
is used to reference other templates.
The file attribute is required to represent the name of the referenced template, and assign represents the output variable that the include file will assign. You can define any number of local variables by yourself using attribute name="attribute value".
include_php
is used to introduce php scripts into templates. file is required to represent the path of the php script. Once determines whether the php script is only loaded once if it is referenced multiple times in the template. Default is true.
insert
is used to include functions in php scripts. name is required and represents the name of the inserted script. Note that if the name is name, the included function is insert_name(), so all Functions to be inserted must be prefixed with insert_. If the assign attribute is used, the output of insert will be assigned to the template variable and will not be displayed. scrīpt indicates the script path to be referenced. The content generated by this program will not be cached and will be re-executed each time the page is called. It is suitable for interactive places such as advertisements, polls, query results, etc.
if, elseif, else
The if statement and condition are similar to php, but each word must be separated by a space. There are also some new conditional statements, listed as follows: eq is equal, ne and neq are not equal, gt is greater than, lt is less than, gte and ge are greater than or equal to, lte and le are less than or equal to, not is not, mod is used to find the modulus. is [not] div by whether it is divisible by a certain number, is [not] even whether it is an even number, $a is [not] even by $b that is ($a / $b) % 2 == 0, is [not] Whether odd is odd, $a is not odd by $b, that is ($a / $b) % 2 != 0
php The
php tag allows the php language to be used directly in the template.
section,sectionelse
section is used to display array data in a loop. name and loop are required parameters. name represents a nested name. Section can be used nested, but the names must be different. loop represents the number of loops. sectionelse outputs when the loop parameter is empty.start is used to specify the pointer to start the loop. If the value is negative, the starting pointer is calculated from the end of the array. The default is 0. step represents the number of steps in the loop. If it is negative, the loop is reversed. The default is 1. max sets the maximum length of the loop. Step number.show determines whether to display section.
section also has its own variable to handle the section attribute, which is displayed using {$smarty.section.sectionname.varname}.
index
index is used to display the current The loop pointer starts from 0.
index_prev
is used to display the pointer of the previous loop, starting from -1
index_next
is used to display the pointer of the next loop.
iteration
Displays the number of current loops, 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
Displays the pointer of the last loop, which can be used in Anywhere in the middle of section, it can also be used after section.
show
show determines whether to display the section.
total
Displays the total number of loops, which can be used in the middle of section anywhere, it can also be used after section.
strip
Remove extra spaces
Regular function
assign
assign is used to assign variable values .var when executing the template, value is a required parameter. var is the name of the variable to be assigned a value, and value is the assigned value.
counter
counter is used to output a count. Multiple counters can be used, but the names must be different .name represents the counter name, the default is default.start represents the initial value of counting, the default is 1.skip counting interval, the default is 1.direction represents the counting direction, up or down, the default is up.print represents whether to print the value, The default is true.assign defines the template variable, and the output of the counter will be assigned to the variable defined by assign.
cycle
Cycle is used to display a set of values in a loop. name represents the cycle name, values("value 1", "value 2",...) represents a set of values displayed in a loop. print indicates whether to display it. advance determines whether to display the next value. delimiter determines the separator of the value, and the default is comma. assign defines the template variable, cycle The output will be assigned to the variables defined by assign.
debug
debug can display all variables assigned values, but does not display the template content. The output attribute determines the displayed format html or javascrīpt. The default is html.
eval
eval is used to insert variables into variables. var is the inserted variable name, and assign assigns the output to a variable.
fetch
is used to get the file content and output the file content. You can get local files, http files and ftp files. file is the path to get the file. assign assigns the output to a variable.
html_checkboxes
html_checkbox is used to create checkboxes with given data. name represents the name of the checkbox, values represents the value of the checkbox, output represents the display of the checkbox, selected represents the value of the selected option, options represents the value and display of a set of checkboxes, separator represents the symbol that separates each checkbox, and labels represents adding to the output. label, defaults to true.
html_image
html_image is used to create html tags for an image. If height and width are not assigned values, they will be automatically generated. file is the path of the image, height, width, alt are the same as the html tag, basedir is the path of the directory starting from the relative path of the image, and the default is the server root directory. href defines the link to the image.
html_options
Output drop-down list, the parameters are name, values, output, selected, options.
html_radios
Output radio button, the parameters are the same as the check box.
html_select_date
prefix defines the prefix of each drop-down list name, the default is Date_. time determines the time to use, and the default is the current time. start_year determines the year in which the drop-down list starts, which can be expressed by the year or the number of years relative to the current year. The default is the current year. end_year determines the year at which the drop-down list ends, which can be expressed by the year or the relative number of years to the current year. The default is the current year. display_days determines whether to display dates. display_months determines whether to display months. display_years determines whether to display the year. month_format determines the format for displaying the month, and the default is %B. day_format determines the format for displaying dates, and the default is %02d. day_value_format determines the format of the date value, the default is %d. month_value_format determines the format of the month value, the default is %m. year_as_text determines whether to output the year in text format. reverse_years determines whether to output each year in reverse. field_array is used to obtain a set of variables. You can obtain the values from the form in the form of name[Day], name[Month], and name[Year]. day_size, month_size, year_size add size tags. all_extra, day_extra, month_extra, year_extra add extra attributes to select or input tags. field_order determines the order of the year, month and day drop-down list, and the default is MDY. field_separator The separator between different drop-down lists. The default is n. year_empty, month_empty, day_empty are the contents 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 is Time_. time determines the time to use, and the default is the current time. display_hours determines whether to display hours. display_minutes determines whether to display minutes. display_seconds determines whether to display seconds. display_meridian determines whether to display morning or afternoon, that is, display am/pm. use_24_hours determines whether to use 24-hour format. minute_interval determines the interval between minutes. second_interval determines the interval in seconds. field_array is used to obtain a set of variables. You can use name[Hour], name[Minute], name[Second] to obtain the value from the form. all_extra, hour_extra, minute_extra, second_extra, meridian_extra add extra attributes to the select or input tag.
html_table
loop defines a set of data for looping. 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 value of the other is calculated based on the number of elements and the valuable attributes. The default value of both is 3. inner determines the enumeration direction of elements. cols arranges columns according to columns, and rows arranges rows according to rows. The default is cols. table_attr, tr_attr, and td_attr add labels to table, tr, and td respectively. If tr_attr and td_attr are arrays, labels will be added in a loop. Trailpad is used to fill cells with no value in the last row. The default is . hdir determines the arrangement direction of elements in each row, from left to right right or from right to left left. The default is right. vdir determines the arrangement direction of each column, from top to bottom down or from bottom to top up. The default is down.
math
Perform numerical operations. equation and var are required. equation defines the operator. The operators that can be used are +, -, /, *, abs, ceil, cos, exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, srans andtan. var assigns a value to the operation variable. format determines the format of the result. assign assigns the output to a parameter.
mailto
Using the mailto function can make it difficult for web spiders to obtain your email address, but it can be displayed normally on the web page because it encrypts the email address. address is required and defines the email address. text is the text content displayed on the page, and the default is the email address. Encode is the way to encrypt the email address. It can be none, hex or javascrīpt. The default is none. If you want to send the email to other mailboxes, you can use cc and separate the email addresses. bcc is blind copy. subject is the subject of the email. Newsgroups are newsgroups for publishing content. Use , to separate newsgroups. extra adds additional tags. I don’t know what followupto means.
textformat
textformat is used to format text. It will remove spaces and special characters, and specify line width and indentation. style specifies the current format, and indent specifies the number of indents. indent_first specifies the indentation of the first line. indent_char is the character used for indentation. The default is a space. wrap specifies the line width, that is, the number of characters in a line. The default is 80. wrap_char specifies the delimiter for each line, the default is n. wrap_cut determines whether to split words. assign assigns the output to a variable.
Constant
SMARTY_DIR
is the full path to the smarty class directory and must end with /. If not defined, the path will be determined automatically.
SMARTY_CORE_DIR
is the full path to the smarty class core file directory and must end with /. If not defined, it will be automatically defined as a subdirectory under the smarty_dir path.
Variable
$template_dir
The default template directory name, the default is "./templates" .
$compile_dir
The default compiled template directory name, the default is "./templates_c"
$config_dir
The default config file directory name, the default is "./configs".
$ plugins_dir
The default plug-in directory name, the default is "plugins".
$debugging
Debugging console. That is, a window that displays variables.
$debug_tpl
Template of the debug window
$debugging_ctrl
Another way to control debugging.
$autoload_filters
Use filters for all templates. This variable is an array, where the keyword is the filter type and the value is the filter name.
$compile_check
Every time php is executed, it will check whether the content of the template has changed.
$caching
Determines whether to cache files generated by file execution.
$cache_dir
The default template cache directory name, the default is "./cache".
$cache_lifetime
The expiration time of the cached template, calculated in seconds. If the $caching value is -1, the cache The template will never expire.
Finally, I will put an example of what I use. Just for reference
error_reporting(7);
$TurnDot = substr( PHP_OS, 0, 3) == 'WIN' ? ";" : ":" ;
$doc_root=$_SERVER['DOCUMENT_ROOT']; //Get the root path by default
//$doc_root="E :/Myweb/an-cool.com/Web" ; //Here is 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"); //Here is loading a global configuration file.
$Templates_root = $doc_root."/ templates"; //Define template root directory
define("Templates",$Templates_root);
$templates = isset($INFO['templates']) ? $INFO['templates'] : 'default ' ;
include_once('Smarty.class.php');
$tpl = new Smarty(); //Create smarty instance object$ tpl
$tpl->debugging = false;
$tpl->template_dir = Templates."/".$templates ; /Set compilation directory
$tpl->cache_dir = $doc_root."/cache"; //Set the cache time
$tpl-> ;cache_lifetime=0; // This is set to false when debugging, please use true when publishing.
$tpl->left_delimiter = '< {';
$tpl->right_delimiter= '}>';
$tpl->assign("template_dir", $INFO['site_url']."/templates/".$templates ) ; //Template path
$tpl->assign("Site_Url", $INFO['site_url']); //Main 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
?>