Smarty is a PHP template engine that separates logical programs from external content and provides an easy to manage approach.
Smarty requires the Web server to run php4.0.6 and more versions.
Smarty installation requires Smarty library files. can go to the official websitehttp://smarty.php.netDownload.
A lot of installation tutorials on the Internet, but I did not succeed, so directly to the entire directory name to Smarty directly copied to the site in the directory, and then open
http://Web site path/smarty/demo/index.php, display normal, should be considered a successful installation.
Basic Syntax
All smarty tags are prefixed with delimiters. In Smarty, everything except the delimiters is static, and when Smarty encounters a template tag, it tries to interpret them and then output it in the right way.
{and} are by default, but they are customizable. The Customization method is:
$smarty->left_delimiter = ' <!--{';
$smarty->right_delimiter = '}--> ';
1. Note
Template comments are surrounded by the * number, for example {* This is a comment *}
Smarty annotations will not be output. It is an intrinsic annotation of the template.
2. Variable
The template variable begins with $ and can contain numbers, letters, and underscores.
Config_file variable is the exception to use # variable name # method reference
3. Function
The Smarty label outputs a variable or calls a function.
Within the delimiter the function and its properties are processed and output. For example:
{funcname attr1= ' val ' attr2= ' Val '}.
FuncName is the name of the function, such as include, ATTR1,ATTR2 is the property name, and Val is the corresponding value of the property.
In a template, both built-in functions and custom functions have the same syntax.
Built-in functions will work inside the smarty, such as {if}, {section}, and {strip}. They can't be modified.
Custom functions work through the plug-in mechanism, which is an additional function that you can modify and add yourself.
For example {html_options} and {html_select_date}
4. Property
Static values do not require quotes, and Boolean values (TRUE or false) do not require quotes, either True,on,yes or False,off,no. But the string exception. Variables are also used, and they cannot be quoted.
5. Insert a variable into a string
You can only identify numbers, letters, underscores, and [] combinations, if you need to "separate" variables for complex forms. For example, {func var= "test $foo. Bar Test"} can only recognize variable $foo, to identify $foo.bar, you need to write the format of {func var= "test" $foo. Bar ' Test '}.
6. How to display some reserved words
In the template, if you want to display some of the reserved words of smarty as the contents of the language, such as displaying delimiters, the default {} method is: {Ldelim},{rdelim} or {$smarty. ldelim},{$smarty. Rdelim} or you can put {} Put in {literal}. {/literal} intermediate output.
reserved variables for smarty
{$smarty} reserved variables can be used to access some special template variables.
The following are all.
Page Request Variable
Here are examples of access to 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} Gets the system environment variable PATH, {$smarty. Request.username} gets get/post/ Cookies/server/env the composite variable.
{$smarty. Now} variable is used to access the current timestamp.
The output can be formatted with the Date_format adjuster. For example {$smarty. Now|date_format: "%y-%m-%d%h:%m:%s"}
{$smarty. Const}
You can access the PHP constants directly. For example {$smarty. Const._my_const_val}
{$smarty. Capture}
You can pass {capture}. The output of the {/CAPTURE} structure interception can be accessed using the {$smarty} variable.
{$smarty. config}
{$smarty} variable can access the config variable that has already been loaded.
For example, {$smarty. Config.foo} can represent {#foo #}.
{$smarty. Section}, {$smarty. foreach}
{$smarty} variables can access the properties of the ' section ' and ' foreach ' loops.
{$smarty. Template}
Displays the name of the template that is currently being processed.
{$smarty. Version}
Displays the version of the Smarty template
{$smarty. Ldelim}
Show Left Separator
{$smarty. Rdelim}
Show Right Separator
Variable Regulator
Variable regulators are used for variables, custom functions, and strings.
can use ' | ' Symbol and adjuster name application adjuster.
The variable regulator determines its behavior by the value given to the parameter.
The parameters are separated by the ': ' symbol.
If you use a variable adjuster to adjust the array variable, the result is that each value of the array is adjusted. If you want the adjuster to adjust the entire array, you must precede the adjuster's name with the @ symbol.
For example: {$articleTitle | @count} (this will be in the output $articleTitle the number of arrays)
Capitalize
Capitalize all the words in the variable in the first word. The parameter value Boolean determines whether a word with a number is capitalized in the first word. Default does not write
count_characters
Calculates the number of characters in a variable value. The Boolean value of the parameter determines whether the number of spaces is computed. No spaces are calculated by default
Cat
Connect the value of the parameter in cat to the given variable. The default is null.
count_paragraphs
Calculate the number of paragraphs in a variable
count_sentences
Calculate 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-a shorthand for the day of the week
%A-The full story of the week
%b-Abbreviations for months
%B-Full writing of the month
%c-Date Time 06/12/05 11:15:10
%c-century time
%d-one month ordinal (from 01 to 31)
%d-same%m/%d/%y
%e-What is the number of one months, the singular is preceded by a space (from 1 to 31)
%g-century
%G-century [0000,9999]
%h-Tong%b
Hours of%h-24 hours (from 00 to 23)
Hours of%i-12 hours (from 01 to 12)
%j-Days of the year (from 001 to 366)
%k-24 hours in the form of a single digit preceded by a space. (from 0 to 23)
%l-12 hours in the form of a single digit preceded by a space. (range 1 to 12)
%m-month (range to 12)
%m-min
%n-line Feed
%p-show morning or afternoon ' am ' or ' PM '
%R-A.M. or p.m. Form of Time
%r-24 hour form of time
%s-Sec
%t-tab symbol
%T-Tong%h:%m:%s
%u-use [1,7] to indicate the day of the week
%u-The calculation is the first few weeks of the year, starting from Sunday of the year
%V-calculated to be the first day of the year, from 01 to 53, the first week must have at least 4 days in this year, Sunday as this week
%w-in digital form is the day ordinal of the week, Sunday is 0
%w-in digital form is the first few weeks of the year, starting from Monday of the year
%x-Display Date: Month/day/year
%x-Display time: Hours: minutes: sec
%y-not including the year of the Century
%Y-including the year of the Century
%Z-time Zone
%%-Output%
Some of them sometimes do not output normally.
default
Default
Set a default value for the empty variable.
When the variable is empty or unassigned, the output is replaced by the given default value.
Escape
Transfer code
The parameter value is Html,htmlall,url,quotes,hex,hexentity,javascript. The default is HTML transcoding
Indent
Indent
Indents the string in each line, the first parameter specifies how many characters to indent, and the default is 4 characters. The second argument specifies what character the indentation replaces.
Lower
Lowercase
This is used to lowercase a variable.
Lowercase the variable string
NL2BR
Replace line breaks with <br/>
Regex_replace
Regular replacement
Find and replace regular expressions. You must have two parameters, and parameter 1 is the replacement of the regular expression. Parameter 2 replaces the text string with the
Replace
Replace
A simple search and replace string must have two parameters, and parameter 1 is the string to be replaced. Parameter 2 is the text to replace
spacify
Spacify inserts a space or other string between each character of a string. A parameter represents a string that will be inserted between two characters, and the default is a space.
String_formatString formatting
is a method of formatting floating point numbers. For example, decimal numbers. Format with sprintf syntax. Parameters are required to specify the format used. %d indicates an integer,%.2f to intercept two floating-point numbers.
StripRemove (extra space)
Replaces all duplicate spaces, newline, and tab to a single or specified string. If there is a parameter, the specified string.
Strip_tagsRemove all HTML tags
truncateIntercept
Parameter 1, which sets the number of characters to intercept. The default is 80.
The second parameter specifies what character to add after the truncated string. Default to ...
The third parameter determines whether the exact interception, by default, is false, and Smarty does not split the word.
UpperChange variable to uppercase
WordWrapRuled constraints
The first argument specifies the width of the paragraph (that is, the number of characters in a row, which wraps more than this character). Default 80.
The second parameter specifies what characters are used at the constraint point (the default is the newline character \ n).
The third parameter determines whether the exact interception of characters, by default is inaccurate interception, that is, interception can not separate words.
Built-in functions
Built-in functions cannot be modified without authorization.
Capture
The role of the capture function is to collect data from the template output into a variable instead of outputting it to the page. For example, any data between {capture Name= "foo"} and {/capture} is received in the variable {$foo} specified by the Name property of the function, or { $smarty. Capture.foo}. If the function does not have a name attribute, "default" will be used. Each {capture} must correspond to {/capture} and cannot be nested using the capture function.
Config_load
Referencing a configuration file
File is required, stating the name of the profile to include in, section describing the name of the part to load, scope of the variable to be processed. Must be local,parent or global.
The local meaning is 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 variables will be applied to all templates. The default is local. Whether the variable is visible on the parent template, and the default is No. If the scope property already has one, this value will be ignored.
Foreach,foreachelse
A foreach loop is an optional section loop. Used to traverse an associative array. Foreach's syntax is much simpler than section, but as a compromise it can only be used for simple arrays.
The parameters that foreach must have are from and item. The from variable represents the name of the array that needs to be cycled, item represents the variable name of the current element, key represents the variable name of the current keyword, and name represents the Foreach loop name that accesses the Foreach property. Loops can be nested, and the names between nested loops must be separate. Foreachelse is executed when the from variable has no value
include
Used to refer to other templates.
The file attribute is required to represent the name of the referenced template, and assign represents the variable of the output that the include file will allocate. You can define any local variable in the way that the attribute name = "Property value".
include_php
Used to introduce PHP scripts into the template. File is a required path to represent the PHP script, once determines if the PHP script is referenced multiple times in the template and is loaded only once. The default is true.
Insert
Used to include a function in a PHP script, name is required to indicate the name of the inserted script, note that if the name is named, the included function is Insert_name (), so all the functions to be inserted have a prefix insert_. If the Assign property is used, the output of the insert is assigned to the template variable and is not displayed. The script represents the path to be referenced. The content generated by this program will not be cached, and be rerun each time the page is invoked, for interactive places such as advertising, polling, query results, etc.
If,elseif,else
If statements and conditions are similar to PHP, but each word must be separated by a space. There are also some new conditional statements, listed below: eq equals, NE, neq unequal, GT is greater than, LT is less than, GTE, GE is greater than equals, LTE, le less than equal, not non, mod modulo. Whether [not] div by can be divisible by a number, is [not] even are even, $a is [not] even by $b that is ($a/$b)% 2 = = 0,is [not] odd are odd, $a is isn't odd by $b ($a/$b)% 2!= 0
PHP
PHP tags allow you to use the PHP language directly in the template.
Section,sectionelse
section is used to loop through the array's data, name and loop are the necessary parameters. Name indicates a nested name. Sections can be nested, but names must be different. Loop represents the number of loops. Sectionelse output that is empty in the loop parameter. Start is used to specify the beginning of the loop pointer, if the value is negative, from the end of the array to calculate the start of the pointer, the default is 0.step to indicate the number of steps of the loop, negative is the reverse loop, the default is the 1.max set the maximum number of steps. Show determines whether the section is
The section also has its own variable handling section attributes, which are displayed with {$smarty. Section.sectionname.varname}.
Index
Index used to display the current loop's pointer, starting at 0.
Index_prev
The pointer used to display the previous loop, starting with-1
Index_next
The pointer used to display the last loop.
Iteration
The number of times the current loop is displayed, starting at 1.
the
True if the current loop is the first loop.
Last
True if the current loop is the last loop.
rownum
With iteration.
Loop
A pointer to the last loop can be used anywhere in the middle of the section, or after a section.
Show
Show determines whether the section is displayed.
Total
Displays the total number of loops, which can be used anywhere in the middle of the section, or after the section.
Strip
Get rid of extra space
General Functions
Assign
Assign is used to assign variable values when the template is executed. Var,value is a required parameter. var is the variable name to assign a value to, value is the assigned values.
counter
Counter is used to output a count. You can use multiple counts, but the names must be different. Name indicates the counter name, the default is Default.start, the default is the interval of 1.skip counting, the default is 1.direction to indicate the direction of counting, up or down, By default, Up.print indicates whether the value is printed, the default is the True.assign definition template variable, and the output of the counter is assigned to the assign defined variable.
Cycle
Cycle is used to iterate through a set of values. Name denotes cycle name, values ("Value 1", "Value 2",...) Represents a set of values that are displayed in a loop. Print indicates whether. Advance determines whether the next value is displayed. Delimiter determines the delimiter for value, which defaults to a comma. Assign defines the template variable, and the output of the cycle is assigned to the assign-defined variable.
Debug
Debug can display all variables assigned a value, but does not display the template content, the output property determines the format HTML or JavaScript that is displayed, and the default is HTML.
Eval
Eval is used to insert variables into a variable. var is the name of the variable that is inserted, and assign assigns the output to a variable.
Fetch
Used to get the contents of the file, and output the contents of the file, you can get local files, HTTP files and FTP files, file is the path to get the files, assign to assign 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 represents the checkbox's display, selected represents the value of the selected option, and the options represent the value and display of a set of checkbox. Separator represents the symbol that splits each checkbox, labels represents the label for the output, and defaults to true.
Html_image
Html_image is used to create HTML tags for a picture, if the height and width unassigned values are automatically generated. File is the path to the picture, Height,width,alt with the HTML tag, Basedir is the path to the directory where the picture is relative to the path, and the default is the server root directory. HREF defines a link to a picture.
html_options
Output Drop-down list, with name,values,output,selected,options parameters.
Html_radios
Output the radio box with the same parameters as the check box.
html_select_date
Prefix defines the prefix for each drop-down list name, and defaults to Date_. Time determines when to use, default is the current time. Start_year determines the year in which the Drop-down list begins, either as a year or as a relative number of years for the current year. The default is the current year. End_year determines the year in which the Drop-down list ends, either as a year or as a relative number of years for the current year. The default is the current year. Display_days determines whether the date is displayed. Display_months Determines whether the month is displayed. Display_years Determines whether the year is displayed. Month_format determines the format for displaying the month, which defaults to%b. Day_format determines the format of the display date, which defaults to%02d. Day_value_format determines the format of the date value, which defaults to%d. Month_value_format determines the format of the month value, which defaults to%m. Year_as_text Determines whether the year is output in text format. Reverse_years determines whether to reverse the output of each year. Field_array is used to obtain a set of variables that can be obtained from a form by using the Name[day],name[month],name[year] method. Day_size,month_size,year_size Add size labels. All_extra,day_extra,month_extra,year_extra add additional attributes to the Select or input label. Field_order determines the order of the list, the default is MDY. Field_separator the separator between different drop-down lists, the default is \ n. Year_empty,month_empty,day_empty is what is displayed in the first column of the Drop-down list.
Html_select_time
Prefix defines the prefix for each drop-down list name, and defaults to Time_. Time determines when to use, default is the current time. Display_hours determines whether to display hours. Display_minutes determines whether the minutes are displayed. Display_seconds determines whether the number of seconds is displayed. Display_meridian decide whether to display the morning or the afternoon, that is, display am/pm. Use_24_hours decide whether the 24-hour system. Minute_interval determines the interval between minutes. Second_interval determines the interval between seconds. Field_array is used to obtain a set of variables that can be obtained from a form by using the Name[hour],name[minute],name[second] method. All_extra,hour_extra,minute_extra,second_extra, Meridian_extra add additional attributes to the Select or input label.
html_table
Loop defines a set of data for looping. COLS determines the number of columns, rows determines the number of rows, if one is empty and the other has a value, the value of the other is computed based on the number of elements and the value of the property, with a default value of 3. Inner determines the enumeration direction of the elements cols columns follow the columns, rows are arranged with rows, and the default is cols. Table_attr,tr_attr,td_attr tags are added to TABLE,TR,TD, and if Tr_attr,td_attr is an array, it will be recycled. Trailpad is used to populate cells with no values in the last row, by default. Hdir determines the direction in which each row of elements is arranged, from left to right, or from right to left, by default. VDir determines the direction in which each column is arranged, from top to bottom down or down to up, and defaults to down.
Math
Perform numeric operations. Equation and Var are necessary. Equation defines the formula, the operators you can use are +,-,/, *, ABS, ceil, COS, exp, floor, log, log10, max, Min, pi, pow, rand, round, sin, sqrt, Sran S and Tan. var assigns a value to an operation variable. Format determines the formatting of the results. Assign assigns the output to a parameter.
mailto
Using the Mailto function can make it difficult for web spiders to get your email address, but it can be displayed normally on a Web page because he encrypts the email address. Address is a must, define email addresses. Text is the textual content that is displayed on the page, and the default is the email address. Encode is the way to encrypt an email address, either None,hex or JavaScript, and the default is None. If you want to send the mail to other mailboxes, you can use cc cc, email address, split between. Bcc is BCC. Subject is the message subject. Newsgroups is a newsgroup that publishes content, separated by newsgroups. Extra add additional labels. Followupto meaning does not know.
TextFormat
TextFormat is used to format text, he removes spaces and special characters, and sets the line width and indentation. Style stipulates the current format, indent the number of digits that are required to indent. Indent_first the indentation of the first line. Indent_char the character used to indent, by default a space. Wrap the line width, that is, the number of characters in one line, default is 80. Wrap_char Specify the delimiter for each line, and the default is \ n. Wrap_cut decide whether to split the word. Assign assigns output to a variable.
Constants
Smarty_dir
is the full path to the Smarty class directory and must be/ended. If not defined, the path is automatically determined.
Smarty_core_dir
is the full path to the Smarty class core file directory and must be/ended. If not defined, it is automatically defined as a subdirectory below the Smarty_dir path.
variable
$template _dir
The default template directory name, which defaults to "./templates".
$compile _dir
The default compilation template directory name, which defaults to "./templates_c"
$config _dir
The default Config file directory name, which defaults to "./configs".
$plugins _dir
The default plug-in directory name, which defaults to "plugins".
$debugging
Debugging console. A window that displays the variable.
$debug _tpl
Template for the Debug window
$debugging _ctrl
Another way to control debugging.
$autoload _filters
Use the filter for all templates, this variable is an array, where the keyword is the type of filter, and the value is the name of the filter.
$compile _check
Each time PHP execution will see if the contents of the template change.
$caching
Determines whether files generated by file execution are cached.
$cache _dir
The default template cache directory name, which defaults to "./cache".
$cache _lifetime
The expiration time of the cached template, measured in seconds. The $caching value is-1 the cached template never expires.
Finally, I'll put in an example that I use. Everybody just make a reference
<?php
Error_reporting (7);
$TurnDot = substr (php_os, 0, 3) = = ' WIN '? ";" : ":" ;
$doc _root=$_server[' Document_root ']; Get root Path by default
$doc _root= "E:/myweb/an-cool.com/web"; This 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"); This is the loading of a global configuration file.
$Templates _root = $doc _root. " /templates "; Define a touch version of the root directory
Define ("Templates", $Templates _root);
$templates = Isset ($INFO [' Templates '])? $INFO [' Templates ']: ' Default ';
Include_once (' Smarty.class.php ');
$TPL = new Smarty (); Establish a Smarty instance object $tpl
$tpl->debugging = false;
$tpl->template_dir = Templates. " /". $templates; Set up template catalogs
$tpl->compile_dir = Templates. " /". $templates." /templates_c "; Setting up the compilation directory
$tpl->cache_dir = $doc _root. " /cache "; Set Cache Directory
$TPL->cache_lifetime = 60 * 60 * 24; Set Cache time
$tpl->cache_lifetime = 0; Set Cache time
$tpl->caching = false; This is set to false at debug time, use True when publishing
$tpl->left_delimiter = ' <{';
$tpl->right_delimiter= '}> ';
$tpl->assign ("Template_dir", $INFO [' Site_url ']. " /templates/". $templates); Touch Board Path
$tpl->assign ("Site_url", $INFO [' Site_url ']); Master 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
?>