Smarty basic syntax

Source: Internet
Author: User
Tags php template split words

Smarty is a PHP template engine that separates logical programs from external content and provides an easy-to-manage method.
Smarty requires the Web server to run php4.0.6 or later.
The smarty library file is required for smarty installation. You can go to the official website http://smarty.php.net download.
I talked about a lot of installation tutorials online, but I did not succeed. So I directly copied the entire directory name to the directory where the website is located, and then opened
Http: // website path/smarty/demo/index. php. The installation is successful.

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 = '<! --{';
$ Smarty-> right_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 example shows the 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 with <br/>

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_formatString 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.

StripRemove (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_tagsRemove all HTML tags

TruncateIntercept
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.

UpperChange the variable to uppercase

WordwrapRow 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 value is 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
Used to include functions 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] Div 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 steps in the cycle. If it is negative, the reverse loop is used. 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 SpacesRegular 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. It can be displayed in the year table or in 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 year relative to 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 normally displayed on the webpage because 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 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 indentation 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.

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.