Smarty tutorial 6

Source: Internet
Author: User
Tags foreach manual function definition function prototype php language mixed php file php and

In the template design section of smarty, I briefly introduced some common settings of smarty in the template. This section mainly introduces How to Start program design in smarty.


First, we will introduce some elements in the. Php file we used in the previous section. Similarly, let's take the index. Php file at the beginning of the previous section as an example:

========================================================== ==========
Index. php
========================================================== ==========

 

<? Php
/*************************************** ******
*
* File name: index. php
* For use: Display instance programs
*
* Author: Master
* Email: teacherli@163.com
*
**************************************** *****/
Include_once ("./comm/Smarty. class. php"); // contains the smarty class file

$ Smarty = new Smarty (); // Create a smarty instance object $ smarty
$ Smarty-> template_dir = "./templates"; // set the template directory
$ Smarty-> compile_dir = "./templates_c"; // Set the compilation Directory


// *** NOTE: I am a new *** here ****//

$ Tpl-> cache_dir = "./cache"; // you can specify a cache directory.
$ Smarty-> cache_lifetime = 60*60*24; // you can specify the cache time.
$ Smarty-> caching = true; // sets the cache mode.

//----------------------------------------------------
// Left and right boundary characters. The default value is {}.
// Conflict, so it is recommended to set it to <{}> or another.
//----------------------------------------------------
$ Smarty-> left_delimiter = "<{";
$ Smarty-> right_delimiter = "}> ";

$ Smarty-> assign ("name", "Li Xiaojun"); // replace Template variables

// Compile and display the index. tpl template under./templates
$ Smarty-> display ("index. tpl ");
?>


As we can see, the smarty program is actually a set of code that complies with the php language specification. Let's explain it one by one:
1. /**/Statement:
The included part is the program header annotation. The main content should be a brief introduction to the role of the program, copyright and the author and the writing time, which is not necessary in the smarty, but in terms of the program style, this is a good style.

2. Include_once statement:
It includes the smarty file installed on the website to the current file. Note that the included path must be correctly written.

3. $ Smarty = new Smarty ():
This statement creates a Smarty object $ smarty, which is a simple object instantiation.

4. $ Smarty-> template_dir = "":
This statement specifies the path for the $ smarty object to use the tpl template. It is a directory. If this statement is not provided, the default template path of Smarty is the templates Directory of the current directory, when writing a program, we need to write this sentence, which is also a good program style.
5. $ Smarty-> compile_dir = "":
This statement specifies the directory when the $ smarty object is compiled. In the template design article, we already know that Smarty is a compilation template language, and this directory is the directory for compiling the template. Note that if the site is located on * nix server, make sure that the directory defined in compile_dir has the write and read permissions. By default, its compiling directory is templates_c under the current directory. For the same reason, we will write it clearly.

6. $ Smarty-> left_delimiter and $ smarty-> right_delimiter:
Specifies the left and right delimiters when searching for template variables. The default values are "{" and "}", but in practice, because we want to use <script> in the template, the function definition in the Script will inevitably use {}, although it has its own solution, we are used to redefining it as "<{" and "}>" or "<! -- {"And"} --> "or other specifiers. Note that if the left and right separators are defined here, in the template file, each variable must use the same symbol as the definition. For example, specify <{"and"}> ", in the tpl template, {$ name} must also be changed to <{$ name}> so that the program can find the template variables correctly.


7. $ Tpl-> cache_dir = "./cache ";:
Tell the template file cache location output by Smarty. In the previous article, we learned that the biggest advantage of Smarty is that it can be cached. Here, we set the cache directory. By default, it is the cache directory under the current directory, which is equivalent to the templates_c Directory. In * nix system, we need to ensure its readability and writability.

8. $ smarty-> cache_lifetime = 60*60*24:

Here, the effective cache time is calculated in seconds. When the first cache time expires, when the caching variable of Smarty is set to true, the cache will be rebuilt. When the value is-1, it indicates that the created cache never expires. If it is 0, it indicates that the cache is always re-established every time the program is executed. The preceding settings indicate that cache_lifetime is set to one day.

9. $ smarty-> caching = 1:
This attribute tells Smarty whether to cache and how to cache it. It can take three values, 0: Smarty default value, indicating that the template is not cached; 1: indicates that Smarty will use the current defined cache_lifetime to determine whether to end the cache; 2: indicates that Smarty uses the cache_lifetime value when the cache is created. Traditionally, true and false are used to indicate whether the cache is performed.

10. $ smarty-> assign ("name", "Li Xiaojun "):
The prototype of this number is assign (string varname, mixed var), varname is the template variable used in the template, and var indicates the variable name to replace the template variable; the second prototype is assign (mixed var). We will explain in detail how to use this member function in the following example. assign is one of the core functions of Smarty, all replace Template variables must use it.

11. $ smarty-> display ("index. tpl "):
Display (string varname) is used to display a template. To put it simply, it displays the templates that have been analyzed and processed. The template file here does not need to be added with a path. You only need to use a file name, the path is defined in $ smarty-> templates (string path.

After the program is executed, we can open the templates_c and cache directories under the current directory, and we will find that there are more % directories below, which are the compilation and cache directories of Smarty, it is automatically generated by the program. Do not directly modify these generated files.
I briefly introduced some common basic elements in the Smarty program. In the following example, you can see that they will be used multiple times.


Next we will introduce a section loop block and a foreach loop block. Originally, it should belong to the template part, but because they are the essence of smarty and closely related to the smarty program design part, so let's talk about it separately in this section.

1. foreach: Used to loop a simple array. It is a selective section loop. Its Definition format is:


CODE: [Copy to clipboard] {foreach from = $ array item = array_id}
{Foreachelse}
{/Foreach}
Here, from indicates the array variable to be cyclic. item is the name of the variable to be cyclic, and the number of loops is determined by the number of array variables specified by from. {Foreachelse} is used for processing when the passed array in the program is empty. The following is a simple example:
========================================================== ===
Example6.tpl
========================================================== ===


<Html>
<Head> <title> This is an example of foreach </title> <Body>
An array will be output here: <br>
<{Foreach from = $ newsArray item = newsID}>
News No.: <{$ newsID. newsID}> <br>
News: <{$ newsID. newsTitle}> <br> <{Foreachelse}>
Sorry, there is no news output in the database!
<{/Foreach}>
</Body>
</Html>
========================================================== =
Example6.php
========================================================== =

 

<? Php
/*************************************** ******
*
* File name: example6.php
* For use: instance program 2 is displayed.
*
* Author: Master
* Email: teacherli@163.com

* Rectification: forest
**************************************** *****/
Include_once ("./comm/Smarty. class. php ");

$ Smarty = new Smarty ();
$ Smarty-> templates ("./templates ");
$ Smarty-> templates_c ("./templates_c ");
$ Smarty-> cache ("./cache ");
$ Smarty-> cache_lifetime = 0;
$ Smarty-> caching = true;
$ Smarty-> left_delimiter = "<{";
$ Smarty-> right_delimiter = "}> ";

$ Array [] = array ("newsID" => 1, "newsTitle" => "1st News ");
$ Array [] = array ("newsID" => 2, "newsTitle" => "2nd news ");
$ Array [] = array ("newsID" => 3, "newsTitle" => "3rd News ");
$ Array [] = array ("newsID" => 4, "newsTitle" => "4th news ");
$ Array [] = array ("newsID" => 5, "newsTitle" => "5th News ");
$ Array [] = array ("newsID" => 6, "newsTitle" => "6th news ");

$ Smarty-> assign ("newsArray", $ array );

// Compile and display the index. tpl template under./templates
$ Smarty-> display ("example6.tpl ");
?>


========================================================== ==========
Example6.php output file
========================================================== ==========
<Html>
<Head> <title> Example of foreach </title> <Body>
An array will be output here: <br>

News No.: 1 <br>
News: 1st news <br>

News No.: 2 <br>
News: 2nd news <br>

News No.: 3 <br>
News: 3rd news <br>

News No.: 4 <br>
News: 4th news <br>

News No.: 5 <br>
News: 5th news <br>

News No.: 6 <br>
News: 6th news <br> </Body>
</Html>

Foreach can also use foreachelse to match and use foreachelse to indicate the operations to be performed by the program when the array passed to foreach is null. For specific usage instructions, see the manual description.

2. section:
The section is designed to solve the problem of foreach. Like foreach, it is used to design the loop blocks in the template. It is complex and can meet the needs of the program greatly, so in the program, I am used to using it instead of using foreach. The basic prototype is:


CODE: [Copy to clipboard] {section name = name loop = $ varName [, start = $ start, step = $ step, max = $ max, show = true]}
Name: section name, no need to add $
$ Loop: the variable to be recycled. In the program, use assign to operate the variable.
$ Start: subscript of the start loop. The subscript of the loop starts from 0 by default.
$ Step: increment of the mark in each loop
$ Max: maximum loop subscript
$ Show: boolean type. Determines whether to display this block. The default value is true.

Here is a glossary:
Loop subscript: Actually, its English name is index, which means index. Here I translate it into "subscript" for better understanding. It indicates the current loop index when the loop block is displayed. The default value starts from 0 and is affected by $ start. If $ start is set to 5, it will also count from 5, we used it in the template design section. This is an attribute of the current {section} and the call method is Smarty. section. sectionName. index. Here, sectionName refers to the name attribute in the function prototype.
The attribute values of the {section} block are:
1. index: the "loop subscript" introduced above. The default value is 0.
2. index_prev: The first value of the current underlying object. The default value is-1.
3. index_next: the next value of the current underlying object. The default value is 1.
4. first: whether it is the first next loop
5. last: whether it is the last loop
6. iteration: number of cycles
7. rownum: current row number, another alias of iteration
8. loop: the last cycle number, which can be used to count the number of cycles of a section after the section block.
9. total: number of cycles. The number of cycles can be counted after the section.
10. show: it is included in the function declaration to determine whether the section is displayed.

For details about their attributes, refer to the manual. You can use these attributes flexibly in the program. I have used the index attribute in the template section.

Similarly, {section} can be used with {sectionelse} to process the template when the input array variable is null.

We use {section} in the above example to replace {foreach} to implement the sample function. Note that in this example, I only use {foreach} in the tpl Template

{Section} is implemented. The php program file is not modified, and the {sectionelse} processing block is added:

========================================================== ===
Example7.tpl
========================================================== ===


<Html>
<Head> <title> This is an example of foreach </title> <Body>
An array will be output here: <br>
<{Section name = loop = $ News}>
News No.: <{$ News [loop]. newsID}> <br>
News Title: <{$ News [loop]. newsTitle}> <br> <{Sectionelse}>
Sorry, there is no news input!
<{/Section}>
</Body>
</Html>
========================================================== =
Example7.php
========================================================== =

 

<? Php
/*************************************** ******
*
* File name: example7.php
* For use: instance program 2 is displayed.
*
* Author: Master
* Email: teacherli@163.com

* Rectification: forest
**************************************** *****/
Include_once ("./comm/Smarty. class. php ");

$ Smarty = new Smarty (); // Create a smarty instance object $ smarty
$ Smarty-> template_dir = "./templates"; // set the template directory
$ Smarty-> compile_dir = "./templates_c"; // Set the compilation Directory

$ Smarty-> cache_dir = "./cache"; // you can specify a cache directory.
$ Smarty-> cache_lifetime = 0;
$ Smarty-> caching = true;
$ Smarty-> left_delimiter = "<{";
$ Smarty-> right_delimiter = "}> ";

$ Array [] = array ("newsID" => 1, "newsTitle" => "1st News ");
$ Array [] = array ("newsID" => 2, "newsTitle" => "2nd news ");
$ Array [] = array ("newsID" => 3, "newsTitle" => "3rd News ");
$ Array [] = array ("newsID" => 4, "newsTitle" => "4th news ");
$ Array [] = array ("newsID" => 5, "newsTitle" => "5th News ");
$ Array [] = array ("newsID" => 6, "newsTitle" => "6th news ");

$ Smarty-> assign ("News", $ array );

// Compile and display the index. tpl template under./templates
$ Smarty-> display ("example7.tpl ");
?>


========================================================== ==========
Example7.php output file
========================================================== ==========
<Html>
<Head> <title> Example of foreach </title> <Body>
An array will be output here: <br>

News No.: 1 <br>
News: 1st news <br>

News No.: 2 <br>
News: 2nd news <br>

News No.: 3 <br>
News: 3rd news <br>

News No.: 4 <br>
News: 4th news <br>

News No.: 5 <br>
News: 5th news <br>

News No.: 6 <br>
News: 6th news <br> </Body>
</Html>

Here, the {section} block feels awkward about the variable naming method, but it doesn't matter. You just need to remember the template variable usage:
$ LoopName [name]. in var mode, loopName is the variable name assigned to the loop, and [name] is the string assigned to the name ,. then you need to set the subscript name corresponding to the value in the program array.


Well, the smarty Learning Guide-program design is written here. For general applications, this knowledge is enough. For other advanced skills, please refer to the examples in the manual, in the next section, we will talk about the examples of Smarty in practical application. We will talk about the implementation of various class libraries in the same example using the mysql statement built in php and the DB class in phplib respectively.

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.