[Tutorial] smarty template engine full tutorial

Source: Internet
Author: User
Tags php template smarty template
ArticleDirectory
    • Iv. html Functions
    • 5. modify template Variables

Auto: http://speedphp.com/post/smarty-advanced.html

 

Smarty Chinese hand NLP http://www.hbcms.com/main/smarty/

 

Smarty template engine full tutorial

The previous section describes how to use the smarty template engine in the speedphp framework. The following describes how to use the smarty template engine in more detail.

This chapter describes some common functions of smarty, allowing you to master the daily development of the smarty template in the shortest time. For more information about the smarty PHP template engine, see the smarty Chinese manual.

I. assigning values to templates

Input variables to the template

Program:

$ This-> Hello = "Hello World ";

Template:

<{$ Hello}>

Output:

Hello World

Input the array to the template

Program:

$ This-> color = array ('red' => 'red', 'yellow' => 'yellow', 'green' => 'green ');

The template can be used:

<{$ Color ['red']}>

You can also:

<{$ Color. Red>

Output:

Red

Ii. template internal syntax

If, elseif, else condition judgment

<{If $ color = "red"}>

This is red.

<{Elseif $ color = "green" | $ color = "white"}>

This is green or white.

<{Else}>

I don't know the color.

<{/If}>

The IF/else in smarty is almost the same as the PHP if/else except that no parentheses are used.

Include include files

<{Include file = "header.html"}>

Please note that the include contains the 'template _ dir' as the root directory, and there is no relative directory. For example, in "template directory/main/footer.html", we will use

<{Include file = "Main/footer.html"}>

.

There is also include_php in smarty, which is the same as include, but include_php contains executable PHP files. At the same time, if you use the include_php function, it may involve the security features of smarty, which is also related to the {PHP} syntax. For more information, see the smarty Chinese manual.

Of course, in Template Development Based on smarty, we do not recommend using PHP functions in the template in principle.

Foreach, foreachelse

Like foreach in PHP, arrays are processed cyclically.

Example: $ this-> color = array ('red' => 'red', 'yellow' => 'yellow', 'green' => 'green ');

<{Foreach item = colorname from = $ Color Key = enname}>

<{$ Enname }>:< {$ colornam}> <br>

<{/Foreach}>

Output:

RED: red

Yellow: Yellow

Green: Green

Multi-dimensional arrays are also processed. Pay attention to the following multi-dimensional arrays:

Example:

$ Students =

Array (

'Name' => 'he qing ',

'Age' => 17,

'Score '=> array (

'Math' => 76,

'Inc' => 92,

'Pe' => 72

),

),

Array (

'Name' => 'Lee wen ',

'Age' => 18,

'Score '=> array (

'Math' => 69,

'English '=> 80,

'Pe' => 79

),

),

);

$ This-> students = $ students;

Template:

Student Score: <br>

<{Foreach item = person from = $ students}>

Name: <{$ person. name}> <br>

Age: <{$ person. Age}> <br>

Score:

<{Foreach item = num key = subject from = $ person. Score}>

<{$ Subject }>:< {$ num}> <br>

<Br>

<{Foreachelse}>

No student data!

<{/Foreach}>

Foreachelse is displayed when the variable is not assigned a value.

Similar to foreach, there are also sections. For details, refer to the smarty Chinese manual.

Literal

Literal is mainly used to display JavaScript scripts that may contain characters such as braces. when these JavaScript scripts are in the {literal} {/literal} tag, the template engine directly displays them without analyzing them.

Sometimes when we use the smarty template, we will encounter a normal program but only output blank pages. Then we can check whether the template contains JavaScript scripts. Adding literal to these JavaScript fields won't be a problem.

<{Literal}>

<Script language = JavaScript>

<! -

Function isblank (field ){

If (field. value = '')

{Return false ;}

Else

{

Document. loginform. Submit ();

Return true;

}

}

//->

</SCRIPT>

<{/Literal}>

Although literal and Strip described below are rarely introduced in general smarty tutorials, literal and strip are very helpful for daily development, especially strip.

Strip

Smarty will clear {strip }... All spaces between {/strip} and carriage return.

We recommend that you use the strip tag in your template immediately. According to the actual development estimation, the strip tag can be used on general pages to reduce the HTML file size by almost 1/4, especially for pages with a large number of contents (such as the homepage), the speed of opening and displaying webpages is significantly improved.

Example:

{Strip}

<Table border = 0>

<Tr>

<TD>

<A href = "{$ URL}">

<Font color = "red"> This is a test </font>

</A>

</TD>

</Tr>

</Table>

{/Strip}

Display:

<Table border = 0> <tr> <TD> <a href = "http://my.domain.com">

<Font color = "red"> This is a test </font> </a> </TD> </tr> </table>

Iii. Functions of the speedphp framework in the smarty Template

In the template, in addition to the built-in functions of smarty, the SP framework also provides some common functions. Let's take a look at the following:

Spurl

Displays a URL address like the result of the spurl () function.

For example:

Program: Echo spurl ('Article', 'LIST', array ('page' => 3, 'pagesize' => 10); // display the third page of the article list

In the template, the following is used:

<{Spurl c = 'Article' A = 'LIST' page = 3 pagesize = 10}>

T

The output result is the same as that of the T () function. The translation results are displayed in multiple languages.

For example:

Program: echo T ("welcome"); // displays the welcome information in a specific language

In the template, it is:

<{T w = 'Welcome '}>

Iv. html Functions

Smarty provides a series of HTMLCodeGenerate a function. The following examples are from the smarty manual. For more information, see the smarty Chinese manual.

Html_checkboxes

Generate multiple selection boxes
Program:
$ This-> cust_checkboxes = array (
1000 => 'Joe schmoe ',
1001 => 'Jack Smith ',
1002 => 'Jane Johnson ',
1003 => 'Charlie brown'
);
$ This-> customer_id '= 1001;
Template:
<{Html_checkboxes name = "ID" Options = $ cust_checkboxes checked = $ customer_id separator = "<br/>"}>
Output:
<Label> <input type = "checkbox" name = "checkbox []" value = "1000"/> Joe Schmoe </label> <br/>
<Label> <input type = "checkbox" name = "checkbox []" value = "1001" Checked = "checked"/> Jack Smith </label> <br/>
<Label> <input type = "checkbox" name = "checkbox []" value = "1002"/> Jane Johnson </label> <br/>
<Label> <input type = "checkbox" name = "checkbox []" value = "1003"/> Charlie Brown </label> <br/>

Html_image

Generate the image IMG tag. html_image automatically obtains the image length and width.
Template:
<{Html_image file = "pumpkin.jpg"}>
Output:

Html_options

to generate multiple drop-down box lists, add the program: $ this-> cust_options = array ( 1000 => 'Joe schmoe', 1001 => 'Jack Smith ', 1002 => 'Jane Johnson ', 1003 => 'Charlie brown' ); $ this-> customer_id '= 1001; template:
<{html_options Options = $ cust_options selected = $ customer_id}>

output:
Joe Schmoe Jack Smith Jane Johnson Charlie Brown

Html_radios

Generate multiple single partitions
Program:
$ This-> cust_radios = array (
1000 => 'Joe schmoe ',
1001 => 'Jack Smith ',
1002 => 'Jane Johnson ',
1003 => 'Charlie brown'
);
$ This-> customer_id '= 1001;
Template:
<{Html_radios name = "ID" Options = $ cust_radios checked = $ customer_id separator = "<br/>"}>
Output:
<Input type = "radio" name = "id []" value = "1000"> Joe Schmoe <br/>
<Input type = "radio" name = "id []" value = "1001" Checked = "checked"> <br/>
<Input type = "radio" name = "id []" value = "1002"> Jane Johnson <br/>
<Input type = "radio" name = "id []" value = "1003"> Charlie Brown <br/>

Html_select_date

Generate year, month, and day drop-down lists
Template:
{Html_select_date month_format = "% m" field_order = "ymd" start_year = "1950 "}

Html_select_time: seconds drop-down box
{Html_select_time use_24_hours = true}

Html_table

Generate a table
Program:
$ This-> DATA = array (1, 2, 3, 4, 5, 6, 7, 8, 9 );
Template:
{Html_table loop = $ data Cols = 4}
Output:
<Table border = "1">
<Tr> <TD> 1 </TD> <TD> 2 </TD> <TD> 3 </TD> <TD> 4 </TD> </tr>
<Tr> <TD> 5 </TD> <TD> 6 </TD> <TD> 7 </TD> <TD> 8 </TD> </tr>
<Tr> <TD> 9 </TD> <TD> & nbsp; </TD> </tr>
</Table>

5. modify template Variables

For the variables entered into the template, sometimes we need to perform some transformation and modification, such as URL encoding for the URL. Next we will introduce several commonly used modifiers)

Default

Default Value
When the variable is null or not assigned a value, the output is replaced by the default value.
For example, <{$ user_name | default: 'tourists'}>. If $ user_name is not assigned a value, "Tourist" is output ".

Escape

Encode strings. Common encoding methods include HTML (HTML transcoding), URL (URL transcoding), JavaScript (JavaScript transcoding), and so on.
Example: $ this-> url = "http://www.163.com ";
Template: <{$ URL | escape: "url"}>
Output: HTTP % 3A % 2f % 2fwww.163.com

LowerLowercaseUpperUppercase

Converts strings in lower or upper case.
Example: $ this-> Hello = "Hello world! ";
Template:
<{$ Hello | Lower}>
Will output Hello world!
<{$ Hello | Upper}>
Will output Hello world!

Replace

Replace, same as str_replace
For example: $ this-> num = "101010101010101 ";
Template: <{$ num | Replace: "1": "0"}> // replace 0 with 1
Output: 111111111111111

Strip_tags

Remove HTML tags, that is, remove the <> intermediate string
Example: $ this-> myword = "<B> Hi </B>, <font color = Red> This is red font. </font> ";
Template: <{$ myword | strip_tags}>
Output: Hi, this is Red font.

In the smarty manual, we can also see some variable modifiers that calculate the string length and intercept the string. However, when using Chinese characters, these variable modifiers cannot be used normally currently. In this case, we can use the spaddviewfunction function of the SP framework to register the functions that can calculate Chinese characters and the functions that correctly intercept Chinese characters into the template, so that these functions can be used like the built-in functions of smarty. In this way, your application functions are more powerful, and the smarty design philosophy is also in line with the template engine function minimization principle.

Of course, the functions T and spurl of the above mentioned speedphp framework in the smarty template are also registered to the template engine through the spaddviewfunction method.

In daily development, we often need to debug the variables input to the template, so we can enable the debugging function of smarty for debugging. For more information, see

 

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.