Smarty Template Basic Syntax

Source: Internet
Author: User
Tags smarty template truncated

Smarty Basic Syntax:

1. Note: <{* This is a comment *}> note that the left and right separators are written in accordance with their own definitions.

<{* I am a Smarty comment, I don ' t exist in the compiled output *}><!--contents are commented and will not be displayed in the page--

2. Variables: template variables starting with dollar sign $, can contain numbers, letters, and underscores, much like PHP variables. You can reference an array of numeric or non-numeric indexes, and of course you can reference object properties and methods.

<{* $abc, $abc 123, $abc _123, $ABC [1], $abc [' a '], $abc->a, $abc->a () These template variables are valid. *}>
Math and Embedding Tags: <{$x + $y}>//                             output x+y and. <{assign var=foo value= $x + $y}>        //attribute variable <{$foo [$x +3]}>                        //variable as an array index <{$foo ={counter}+3}>                  //tags nested inside tags <{$foo = "This is message {counter}"}>  //quotation mark inside use label Definition array: <{assign var=foo value=[1,2,3]}><{assign var=foo value=[' y ' = ' yellow ', ' b ' = ' Blue ']}><{ Assign Var=foo value=[1,[9,8],3]}>   //Can be nested

3. Functions

<{* each smarty tag output a variable or call a function. Within the delimiter function (the general delimiter ' {} ') and its properties (also within the delimiter) will be processed and output.
For example: {funcname attr1= "val" attr2= "Val"} *}> the first argument is the function name, the second argument is the parameter name, and the third parameter is the parameter value.
{config_load file= "colors.conf"}//parameter named Config_load, parameter name is file, parameter value is colors.conf. {include file= "HEADER.TPL"} {if $highlight _name}    Welcome, <font color= "{#fontColor #}" >{$name}!</font>    {Else}    Welcome, {$name}!{ /if}{include file= "Footer.tpl"}

4. Properties: The properties of the Smarty function are much like those in HTML. The static values do not need to be quoted, but the strings suggest using quotation marks. You can use normal smarty variables, or you can use variables with regulators as attribute values, and they do not have to be quoted. You can even use PHP function return values and complex expressions as property values. Some properties use Boolean values (True or false), which indicate true or false. If you do not assign a Boolean value to these properties, the default is to use True for its value.

{include file= "HEADER.TPL"}
{include file= "Header.tpl" NoCache} equals nocache=true
{include file= "HEADER.TPL" attrib_name= "attrib value"}//these are attributes, = preceded by the property name, followed by the property value.
{Include file= $includeFile}
{include file= #includeFile # title= "My title"}
{Assign Var=foo Value={counter}} Plugin result
{Assign Var=foo value=substr ($bar, 2,5)} PHP function Result
{Assign Var=foo value= $bar |strlen} Using the regulator
{Assign Var=foo value= $buh + $bar |strlen} More complex expressions
{Html_select_date Display_days=true}
{mailto address= "[email protected]"}<select name= "company_id" >
{html_options options= $companies selected= $company _id}</select>

5. Embedded variable in double quotes

Smarty can identify variables embedded in double quotes as long as the variable contains only numbers, letters, underscores, and brackets [], and for other symbols (periods, object references, and so on) this variable must be wrapped with two anti-quotes ' (This symbol and ~ ' On the same key, usually below the ESC key).

Smarty3 added double quotes to support smarty tags. This is useful in situations where you need to include a regulator variable, a plug-in, and a PHP function return value.

{func var= "Test $foo test"}              Displays the $foo, parsing the contents between 2 test items.
{func var= "test $foo _bar Test"} Display $foo _bar, can parse out _.
{func var= ' test ' $foo [0] ' test '} Show $foo [0], support "and [] parsing.
{func var= ' test ' $foo [bar] ' test '} Display $foo [bar], support "and [] resolution.
{func var= "test $foo. Bar Test"} Show $foo (instead of $foo.bar) Smarty only recognizes variable $foo, others output as original
{func var= ' Test ' $foo. Bar ' Test '} Display $foo. Bar with anti-quote, Smarty can identify variable $foo.bar
{func var= ' Test ' $foo. Bar ' Test ' |escape}//regulator in the introduction
{func var= "test {$foo |escape} test"} The regulator is inside the quotation marks
{func var= "test {time ()} Test"} PHP function Results
{func var= ' Test {counter} Test '//plugin result
{func var= "variable foo is {if! $foo}not {/if} defined"}//Smarty block function

6. Mathematical operations: Mathematical operations can directly affect the value of the variable.

{$foo +1}//add directly {$foo * $bar}//directly multiplies {$foo->bar-$bar [1]* $baz->foo->bar () -3*7}//take the elements of the class multiplied

7. Ignore Smarty parsing: Sometimes, ignoring smarty is necessary for parsing certain segments of a sentence. A typical scenario is a JavaScript or CSS code embedded in a template. The reason is that these languages use the same symbols as the Smarty default delimiter ' {' and '} '.

{Literal}//literal is the tag of the Smarty template, which specifies that the contents are not parsed. function Bazzy {alert (' foobar! ');} Content that does not need to be parsed {/literal}//end tag

Smarty variable

1. Variables assigned from PHP

Smarty has several different types of variables, and the type of the variable depends on what its prefix symbol is (or what symbol it encloses).

Smarty variables can be directly output or as parameters of function properties and regulators (modifiers), or for internal conditional expressions and so on. If you want to output a variable, just surround it with a delimiter.

For example: The following is the variable $ A registered to Smarty inside, the name becomes Ceshi. Supports common variables, indexed arrays, associative arrays, objects, and so on.

<?php//introduces the configuration file include (".. /init.inc.php ");//init.inc.php has built Smarty objects inside. $a = "Hello";
$attr = Array (1,2,3,4,5);
$attr 1 = Array ("One" = "111", "one" = "222");

Class Ren
{
Public name= "Zhang San";
}
$r = new Ren ();
$smarty->assign ("Ceshi", $a);//injection variable
$smarty->assign ("Shuzu", $attr);
$smarty ("Guanlian", $attr 1);
$smarty ("Duixiang", $r);
$smarty->display ("test.html");//Invoke template file to display

HTML page parsing method

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><{$duixiang->name}><!--Parse the contents of the object--
</body>

2. (1) Simple configuration file

Variables read from the configuration file

After the configuration file is loaded, the variables in the configuration file need to be surrounded with two pound "#" or smarty reserved variable $smarty.config. To invoke (as described in the next section), the second syntax is useful when the variable is embedded in the quotation marks as a property value, and in detail can refer to the embedding of values in double quotes.

Example: Take the configuration file configs inside the file test.conf, inside the file as shown.

Here is the code that takes the contents of the configuration file

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

Show results as

This means that you can use this method to remove the properties in the configuration file, you can directly modify the contents of the configuration file to modify the property values.

(2) Complex configuration files

In the configuration file, if the text is in the # #里面, the description is a comment, is not read out.

If [] appears, the representative has divided the configuration file into chunks, from [] start to the next [] content is a block. Here is the contents of the Read block:

Contents of the configuration file: There are 2 blocks inside.

Code to read:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

3.{$smarty} reserved variables

(1) Request variables page requests variable

Request variables such as $_get, $_post,$_cookie, $_server, $_env and $_session can be used directly. Here's how to output variables.

<{$smarty .get.page}><!--in the middle is the method of taking variables,. The variable name is followed by the following value method--><{$smarty. post.page}><{$ smarty.cookies.username}><{$smarty. server.server_name}><{$smarty. env.path}><{$ smarty.session.id}><{$smarty .request.username}>

(2) {$smarty. Now}

<{$smarty .now}><!--output is timestamp--

(3) {$smarty. const} represents a constant

Now the test.php page defines a constant

Define ("AA", "Hello");//define represents a constant

Read constants:

<{$smarty .const.aa}>

The result of the output is hello.

(4) {$smarty. Capture}

The built-in {capture} can be captured by {$smarty. Capture} variable ... {/capture} template output.

(5){$smarty. config}

{$smarty. config} can get configuration variables.

<{$smarty .config.color}><!--can also read the contents of the configuration file directly--

(6){$smarty. Section}

{$smarty. Section} is used to point to the property of the {section} loop, which contains some useful values.

(7) {$smarty. Template}

Returns the currently processed template name (excluding directories).


(8) {$smarty. Current_dir}

Returns the current directory name of the processed template.

(9){$smarty. version}

Returns the compiled Smarty template version number.

4. Variable Adjuster

A variable adjuster acts on a variable, a custom function, or a string. The use of a variable adjuster is: ' | ' The symbol right-click the regulator name. Variable regulators can receive additional parameters that affect their behavior. The parameters are located on the right side of the adjuster and separated by the ': ' symbol.

(1) Capitalize

Capitalize the first word of all the words in the variable. It is similar to PHP's Ucwords () function. The wording is as follows:

<{$articleTitle |capitalize}><!--The first argument is the name of the variable, separated by |, followed by a capitalize (equivalent to a parameter)--

(2) Cat

The value in Cat is followed by the given variable. That is, the connection string. The wording is as follows:

<{$articleTitle |cat: "Yesterday"}><!--the first argument is a variable name, separated by |, followed by CAT, followed by a string to concatenate--

(3) Count_characters

Calculates the number of characters in a variable. The wording is as follows:

<{$articleTitle |count_characters}><!--The first argument is the variable name, | followed by the method count_characters-->

(4) Count_sentences

Calculates the number of sentences in a variable. The wording is as follows:

<{$articleTitle |count_sentences}><!--The first argument is the variable name, | followed by the method count_sentences-->

(5) Date_format

This regulator will format the date and time by PHP function strftime () processing. The Unix timestamp, the MySQL timestamp, and the date of the string format made up of month and day can be passed to Smarty by PHP function Strtotime () parsing. The designer can use Date_format to fully control the date format, and if the date passed to Date_format is null, but the second argument is provided, the second parameter is used to format the time.

<{$smarty. Now|date_format: ""%y-%m-%d%h:%m:%s}><!--convert timestamps to time--

(6) Indent

The string is indented in each line, and the default is 4 characters. For the first optional parameter, you can specify the number of indent characters, and for the Second optional parameter, you can specify what character indents are used, such as ' \ t ' as tab.

(7) Replace

A simple process of searching and replacing strings in a variable. Equivalent to PHP's Str_replace () function.

(8) Strip

Replaces all repeating spaces, line breaks, and tabs with a space or a given character.

(9) Truncate

A length character is truncated from the beginning of the string, which is 80 by default, and you can also specify the second argument as the text string appended to the truncated string. The append string is computed in the intercept length. By default, Smarty is truncated to the end of a word. If you want to accurately intercept the number of characters, change the third parameter to "true".

Smarty Template Basic Syntax

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.