Dynamic Web Authoring Skills PHP: Learn smarty in detail

Source: Internet
Author: User
Tags php template smarty template
Dynamic Web page Authoring tips PHP: Learn more thoroughly smarty
Smarty is a PHP template engine that separates logic programs from external content and provides an easy-to-manage approach.

Smarty requires the Web server to run php4.0.6 and later.

Smarty installation requires Smarty library files. can go to the official website http://smarty.php.net download.

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 directory where the site, and then open
http://Web site path/smarty/demo/index.php, the display is normal, should be considered as successful installation.


Basic syntax

All Smarty tags are added with delimiters. In Smarty, all content other than the delimiter is static, and when Smarty encounters a template tag, it tries to interpret them and then output them in the proper way.

{and} are by default, but they are customizable. Custom methods are:
$smarty->left_delimiter = ' ';

1. Notes

The template comment is surrounded by an * number, for example {* This is a comment *}
Smarty comments will not be output. It is the inner comment of the template.

2. Variables
The template variable starts with $ and can contain numbers, letters, and underscores.
The Config_file variable is the exception to use the # variable name # method reference

3. Functions
The smarty tag outputs a variable or calls a function.
Within the delimiter function and its properties will be 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 the template, both the built-in function and the custom function have the same syntax.
The built-in functions will work inside smarty, such as {if}, {section}, and {strip}. They cannot be modified.
Custom functions work through plug-in mechanisms, which are additional functions that can be arbitrarily modified and added by themselves.
For example {html_options} and {html_select_date}

4. Properties
Static values do not need to be quoted, and Boolean values (TRUE or false) do not require quotation marks, either True,on,yes or False,off,no. But the string is the exception. Variables are also used, and they cannot be quoted.

5. Inserting a variable in a string
Only a combination of numbers, letters, underscores and [] can be recognized, and if complex forms need to be separated by a variable. For example {func var= "test $foo. Bar Test"} can only recognize the variable $foo, to identify the $foo.bar, you need to write {func var= "test" $foo. Bar ' Test "} format.

6. How to display some reserved words
In the template, if you want to display some of Smarty's reserved words as language content, such as display separators, the default 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 variables
The following are examples of accessing 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/ The compound variable of the cookies/server/env.

{$smarty. Now} variable is used to access the current timestamp.
The output can be formatted with the Date_format regulator. 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}
You can pass {capture}. The output of the {/CAPTURE} structure interception can be accessed using the {$smarty} variable.

{$smarty. config}
The {$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 delimiter

{$smarty. Rdelim}
Show Right delimiter
Variable adjuster
Variable conditioners are used for variables, custom functions, and strings.
You can use ' | ' Symbol and adjuster name apply regulator.
A variable adjuster determines its behavior by the value given to the parameter.
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 regulator to adjust the entire array, [email protected]
For example: [email protected]} (this will be in the output $articleTitle the number of arrays)

Capitalize
Capitalize the first word of all the words in the variable. The Boolean value of the parameter determines whether the word with a number is capitalized in the first word. Default not written

Count_characters
Calculates the number of characters in a variable's value. The parameter value Boolean determines whether the number of spaces is calculated. No spaces are calculated by default

Cat
Connect the parameter values in cat to the given variable. Default is empty.

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 format of the date.
If the data passed to Date_format is empty, the second parameter will be used as the default time

%a-shorthand for the day of the week

%A-Full write of the day of the week

%b-Shorthand for the month

%B-Full write of the month

%c-DateTime 06/12/05 11:15:10

%c-century time

%d-the number of one months (from 01 to 31)

%d-same%m/%d/%y

%e-What is the number of the one-month period, with a space (from 1 to 31) in front of the singular?

%g-century

%G-century [0000,9999]

%h-the same%b

Hours in%h-24 hours (from 00 to 23)

Hours in%i-12 hours (from 01 to 12)

%j-the day 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 12)

%M-min

%n-line break

%p-show morning or afternoon ' am ' or ' PM '

%R-A.M. or p.m. form of time

%r-24 hours form of time

%s-Sec

%t-tab symbol

%T-the same%h:%m:%s

%u-with [1,7], which represents the day of the week

%u-calculation is the first week of the year, beginning in Sunday of the year

%V-Calculation is the first week of the year, from 01 to 53, the first week must have at least 4 days in this year, Sunday as the day of the week

%w-the day of the week is expressed as a number, and Sunday is 0

%W-A number in the form of the first few weeks of the year, beginning in Monday of the year

%x-Show Date: Month/day/year

%x-Show time: Hours: minutes: seconds

%y-not including the year of the Century

%Y-including the year of the Century

%Z-time Zone

Percent-output%

Some of them sometimes fail to output normally.

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

Escape
transcoding
The parameter value is Html,htmlall,url,quotes,hex,hexentity,javascript. The default is HTML transcoding

Indent
Indent in
Indents the string at each line, the first parameter specifies how many characters are indented, and the default is 4 characters. The second argument, which specifies what character indentation is substituted for.

Lower
Lowercase
This was used to lowercase a variable.
Lowercase the variable string

Nl2br
Replace line breaks with


Regex_replace
Regular replacement
Find and replace regular expressions. There must be two parameters, and parameter 1 is the replacement of the regular expression. Parameter 2 What text string to use to replace

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

Spacify
Spacify is to insert a space or other string between each character in the string. The parameter represents a string that will be inserted between two characters, and the default is a space.

String_format string Formatting
is a method for formatting floating-point numbers. For example, decimal number. Formatted using sprintf syntax. The parameter is required, and the formatting method used is specified. %d indicates that an integer is displayed, and%.2f indicates that two floating-point numbers are intercepted.

Strip removal (extra spaces)
Replace all repeating spaces, wrap and tab to a single or specified string. The specified string if there is a parameter.

Strip_tags Remove All HTML tags

Truncate intercept
Parameter 1, which specifies the number of characters to intercept. The default is 80.
The second parameter specifies what character to add after the truncated string. The default is ...
The third parameter determines whether to intercept accurately, false by default, and Smarty does not divide words.

Upper changing a variable to uppercase

WordWrap line width constraint
The first parameter specifies the width of the paragraph (that is, how many characters are in a row, which is more than the number of characters wrapped). Default 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 the character is intercepted accurately, by default it is not accurately intercepted, or the word cannot be separated when intercepted.
Built-in functions
The built-in function cannot be modified without authorization.
Capture
The function 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 by the variable {$foo} specified by the function's Name property, or { $smarty. Capture.foo}. If the function does not have a name attribute, the "default" is used. Each {capture} must correspond to {/capture}, nor can it be nested using the capture function.

Config_load
Referencing a configuration file
File is required to include the name of the profile to be included, the section describes the name of the part to be loaded, scope of the variable to be processed by scope. Must be local,parent or global.
Local means that the variable will be loaded in this template.
The parent means that the variable will be loaded in this template and the parent template.
Global means that the variable will be applied to all templates. The default is local. If the variable is visible in the parent template, the default is No. If the scope attribute is already available, this value will be ignored.

Foreach,foreachelse
The Foreach loop is a selective section loop. Used to traverse associative arrays. The syntax of foreach is much simpler than the section, but as a compromise it can only be used for simple arrays.
The arguments that foreach must have 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, 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 with each other, and the names between nested loops must be independent. Foreachelse is executed when the from variable has no value

Include
Used to refer to other templates.
The file property is required to represent the name of the referenced template, and assign represents the variable of the output that the include file will be assigned. You can define any local variable by yourself using the property name = "attribute value".

include_php
Used to introduce PHP scripts into the template. File is required to represent the path to the PHP script, once determines if the PHP script is referenced multiple times in the template, and whether it is loaded only once. The default is true.

Insert
Used to include functions in a PHP script, name is required, indicates the name of the script being inserted, and note that if the name is named, the containing function is Insert_name (), so all functions to be inserted are prefixed with insert_. If the Assign property is used, the output of the insert is assigned to the template variable and is not displayed. Script indicates the path of the scripts to be referenced. The content generated by this program will not be cached, re-executed every time the page is invoked, applicable to ads, polls, query results and other interactive places.

If,elseif,else
The IF statement and the condition are similar to PHP, but each word must be separated by a space. There are some new conditional statements, listed as follows: Eq equal, NE, neq unequal, GT greater than, LT is less than, GTE, GE greater than equals, LTE, le less than equals, not non, mod modulo. is [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 whether it is odd, $a is isn't odd by $b ($a/$b)% 2! = 0

Php
PHP tags allow you to use the PHP language directly in your template.

Section,sectionelse
section is used to iterate through the data of an array, name and loop are required parameters. Name indicates a nested name. Sections can be nested, but names must be different. Loop indicates the number of cycles. Sectionelse the output of the loop parameter is empty. Start is used to specify a pointer for the start of the loop, if the value is negative, the starting pointer is calculated from the end of the array, the default is 0.step for the number of steps in the loop, negative for the reverse loop, and the default is 1.max to set the maximum number of steps for The loop. Show determines whether the section
Section also has its own Variable handling section property, which is displayed with {$smarty. Section.sectionname.varname}.

Index
Index is used to display a pointer to the current loop, starting at 0.

Index_prev
A pointer to show the previous loop, starting with-1

Index_next
The pointer used to display the last loop.

Iteration
Displays the current number of cycles, starting at 1.

First
The value is true if the current loop is the first loop.

Last
The value is true if the current loop is the last loop.

RowNum
With iteration.

Loop
Displays a pointer to the last loop, which can be used anywhere in the middle of a section, or after a section.

Show
Show decides whether to show section.

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

Strip
Remove the extra space
General functions
Assign
The 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 the value to, and value is the one assigned.

Counter
The counter is used to output a count. Multiple counts can be used, but the names must be different. Name represents the counter name, default is Default.start, which is the initial value for the count, the default is the interval of 1.skip count, the default is 1.direction to indicate the count direction, up or down, By default, Up.print indicates whether the value is printed, the template variable is defined by default for True.assign, and the output of the counter is assigned to assign defined variables.

Cycle
Cycle is used to cycle through a set of values. Name indicates the cycle name, values ("Value 1", "Value 2",...) Represents a set of values that are displayed in a loop. Print indicates whether or not to display the. Advance determines whether the next value is displayed. Delimiter determines the delimiter for value, which defaults to a comma. Assign defines a template variable, and the output of cycle is assigned to the variable defined in the Assign.

Debug
Debug can display all variables that are assigned a value, but the template content is not displayed, 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 variables. var is the name of the inserted variable, and assign assigns the output to a variable.

Fetch
Used to obtain 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 obtain files, assign to assign the output to a variable.

Html_checkboxes
The Html_checkbox is used to create a checkbox with the given data. The name represents a CheckBox, values represents the value of the checkbox, output indicates the display of the checkbox, selected represents the value of the selected option, and the options represents the value and display of a set of checkboxes. The separator represents the symbol that splits each checkbox, labels indicates that the output is labeled, and the default is true.

Html_image
Html_image is used to create an HTML tag for a picture, and 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 image is relative to the path, and defaults to the server root directory. HREF defines the link to the picture.

Html_options
Output drop-down list, parameters are name,values,output,selected,options.

Html_radios
Output Radio box, parameter with check box.

Html_select_date
Prefix defines the prefix for each drop-down list name, which defaults to Date_. Time is used to determine the current time, which is the default. Start_year determines the year in which the drop-down list starts, which can be expressed in years, or as a relative number of years in the current year. The default is the current year. End_year determines the year in which the drop-down list ends, either in years or as a relative number of years in 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 of the month, which defaults to%b. Day_format determines the format of the date, which defaults to%02d. The Day_value_format determines the format of the date value, which is%d by default. 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 using the Name[day],name[month],name[year] method. Day_size,month_size,year_size Add a size label. All_extra,day_extra,month_extra,year_extra add additional attributes to the Select or input tag. Field_order determines the order of the Month Kusakabe drop-down list, which defaults to MDY. Field_separator the delimiter between different drop-down lists, which is \ n by default. Year_empty,month_empty,day_empty is what appears in the first column of each drop-down list.

Html_select_time
Prefix defines the prefix for each drop-down list name, which defaults to time_. Time is used to determine the current time, which is the default. Display_hours decide whether to show hours. Display_minutes decide whether to show minutes. Display_seconds determines whether the number of seconds is displayed. Display_meridian decide whether to show morning or afternoon, that is, show am/pm. Use_24_hours decide whether to make a 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 using the Name[hour],name[minute],name[second] method. All_extra,hour_extra,minute_extra,second_extra, Meridian_extra adds additional attributes to the Select or input tag.

Html_table
Loop defines a set of data that is used 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, and the default value for both is 3. Inner determines the enumeration direction of the element cols the column is arranged, rows are followed by rows, and the default is cols. Table_attr,tr_attr,td_attr Add tags for table,tr,td, and if Tr_attr,td_attr is an array, it will loop to add tags. The Trailpad is used to populate cells with no value for the last row, by default. Hdir determines the direction in which each line of elements is arranged, from left to right or right to left, by default. VDir determines the direction of each column, from top to bottom down or down to up, by default.

Math
Perform a numeric operation. Equation and Var are required. Equation defines the equation, the operator that can be used is +,-,/, *, 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 result. 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 on the Web page as he encrypts the email address. Address is a must, define an email address. Text is the textual content 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, which is none by default. If you want to send the mail to other mailboxes, you can use cc cc, email address between, split. Bcc is BCC. Subject is the subject of the message. A newsgroups is a newsgroup that publishes content, separated by a group of newsgroups. Extra add additional tags. Followupto means I don't know.

TextFormat
TextFormat is used to format text, he removes spaces and special characters, and specifies line width and indentation. style Specifies the current format, indent specifies the number of digits to indent. INDENT_FIRST Specifies the indentation of the first line. Indent_char the character used to indent, the default is a space. Wrap specifies the line width, which is the number of characters on a line, which defaults to 80. WRAP_CHAR Specifies the delimiter for each line, which is \ n by default. Wrap_cut decide whether to divide the words. Assign assigns the output to a variable.
Constant
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 end with/. 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
Default compile template directory name, default 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 variables.
$debug _TPL
Templates for Debug windows
$debugging _ctrl
Another way to control debugging.
$autoload _filters
For all templates using the filter program, this variable is an array, where the keyword is the filter type, and the value is the filtered name.
$compile _check
Each time the PHP execution will see if the contents of the template change.

$caching
Determines whether to cache files to execute the generated files.
$cache _dir
The default template cache directory name, which defaults to "./cache".
$cache _lifetime
The expiration time of the cached template, in seconds. $caching a value of 1 the cached template never expires.

Finally, let me put an example I use. Let's just make a reference.

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"; 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 a global configuration file loaded.
$Templates _root = $doc _root. " /templates "; Define the root directory of the version
Define ("Templates", $Templates _root);
$templates = Isset ($INFO [' Templates '])? $INFO [' Templates ']: ' Default ';
Include_once (' Smarty.class.php ');
$TPL = new Smarty (); Establish the Smarty instance object $tpl
$tpl->debugging = false;
$tpl->template_dir = Templates. " /". $templates; Set up a template directory
$tpl->compile_dir = Templates. " /". $templates." /templates_c "; Set compilation directory
$tpl->cache_dir = $doc _root. " /cache "; Set the 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 when debugging, use True when publishing
$tpl->left_delimiter = ' <{';
$tpl->right_delimiter= '}> ';
$tpl->assign ("Template_dir", $INFO [' Site_url ']. " /templates/". $templates); Trackpad path
$tpl->assign ("Site_url", $INFO [' Site_url ']); Main Station 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
?>
  • 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.