Go PHP template Smarty Simple Getting Started tutorial

Source: Internet
Author: User
Tags php language php template

Turn the--http://blog.163.com/[email protected]/blog/static/166861361201062595057962/

How to start our journey in Smarty
The design of the sequence.
PHP Code:--------------------------------------------------------------------------------
Let's start by introducing some of the elements in the. php file that we used in the previous section. Again, let's take a look at the first index.php file in the previous section to illustrate:

================================================
index.php
================================================

<?php
/*********************************************
*
* File name: index.php
* Function: Show instance Program
*
* Author: Big bro
* Email: [Email protected]
*
*********************************************/
Include_once ("./comm/smarty.class.php"); Contains the Smarty class file
$smarty = new Smarty (); Establish the Smarty instance object $smarty
$smarty->templates ("./templates"); Set up a template directory
$smarty->templates_c ("./templates_c"); Set compilation directory
Look, I'm the new ****//I'm joining here.
$smarty->cache ("./cache"); Set the cache directory
$smarty->cache_lifetime = 60 * 60 * 24; Set Cache time
$smarty->caching = true; Set Cache mode

//----------------------------------------------------
Left and right boundary character, default to {}, but practical application is easy with JavaScript
It is a conflict, so it is recommended to set up <{}> or other.
//----------------------------------------------------
$smarty->left_delimiter = "<{";
$smarty->right_delimiter = "}>";
$smarty->assign ("name", "Li X.J."); Make template variable substitution

Compile and display the Index.tpl template located under./templates
$smarty->display ("Index.tpl");
?>

We can see that the Smarty program part is actually a set of code that conforms to the PHP language specification, which we'll explain in turn:
1. /**/statement:
The included section is the program header comment. The main content should be the role of the program, copyright and author and writing time to do a simple introduction, which is not required in Smarty
Required, but in terms of the style of the program, this is a good style.

2. Include_once statement:
It will install the Smarty file to the Web site into the current file, note that the included path must be written correctly.
3. $smarty = new Smarty ():
This sentence creates a new Smarty object $smarty, a simple instantiation of an object.
4. $smarty->templates (""):
This sentence indicates the path of the $smarty object when using the TPL template, which is a directory in which the default template path is smarty the current directory templates
Table of contents, the actual writing process, we have to write this sentence, which is also a good procedural style.
5. $smarty->templates_c (""):
This sentence indicates the directory at which the $smarty object was compiled. In the template design we already know that Smarty is a compiled template language, and this directory is what it compiles
Template directory, note that if the site is located on a *nix server, make sure that the directory defined in Teamplates_c has write-readable permissions, by default it compiles the directory
is the current directory of Templates_c, for the same reason we write it clearly.

6. $smarty->left_delimiter and $smarty->right_delimiter:
Indicates the left and right delimiters when a template variable is found. The default is "{" and "}", but in practice because we want to use the function in <script>,script in the template
Righteousness will inevitably use {}, although it has its own solution, but it is customary for us to redefine it as "<{" with "}>" or "<!--{" and "}-->" or other glyphs, note that if here
After defining the left and right delimiters, in the template file corresponding to each variable to use the same as the definition of the symbol, for example, here is specified as "<{" and "}>", the TPL template will also be the corresponding
{$name} becomes <{$name}&gt, so that the program can find the template variable correctly.

7. $smarty->cache ("./cache"):
Tells the location of the Smarty output template file cache. The previous article we know Smarty the biggest advantage is that it can be cached, this is the directory to set the cache. Default situation
The cache directory under the current directory, comparable to the Templates_c directory, in the *nix system we want to ensure that it is readable and writable.

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

This will be the time in seconds to calculate the cache validity. When the first cache time expires, the cache is rebuilt when the caching variable of Smarty is set to true. When it's
A value of 1 indicates that the established cache never expires, and 0 indicates that the cache is always re-established every time the program executes. The above setting indicates that the Cache_lifetime is set to one day.
9. $smarty->caching = 1:
This property tells Smarty whether to cache and how to cache. It can take 3 values, 0:smarty the default value, indicating that the template is not cached; 1: Represents
Smarty will use the currently defined cache_lifetime to decide whether to end Cache;2: Indicates that smarty will use the value Cache_lifetime when the cache is built. Accustomed to make
Use True and false to indicate whether to cache.
$smarty->assign ("name", "Li X.J."):
The prototype for this number is assign (string varname, mixed Var), varname is the template variable used in the template, var indicates the variable name to replace the template variable;
The second prototype is assign (mixed Var), we want to explain in detail the use of this member function in the following example, assign is one of the core functions of smarty, all the changes to the template
Use it to replace the volume.
One. $smarty->display ("Index.tpl"):
The function is a prototype of display (string varname), which acts as a template. Simply put, it will parse the processed template display, where the template file does not
With the add path, as long as you use a file name, it is the path we have defined in $smarty->templates (string path).
After the execution of the program we can open the current directory of the Templates_c and the cache directory, you will find a few more than a few percent of the directory, these directories are Smarty compilation and
The cache directory, which is generated automatically by the program, and does not modify these generated files directly.
I briefly introduced some of the common basic elements in the Smarty program, and in the example below you can see that they will be used more than once.


Next, we introduce a section loop block and a foreach loop block, which should belong to the template part, but because they are the essence of smarty, and with Smarty programming
Part of the connection is very close, so just take it out in this section alone.
1. Foreach: Used for looping a simple array, which is a selective section loop, which is defined in the following format:

{foreach from= $array item=array_id}
{Foreachelse}
{/foreach}
Where from indicates the array variable to loop, item is the name of the variable to loop, and the number of cycles is determined by the number of array variables specified by the FROM. {Foreachelse} is used when
The array passed in the program is treated as empty, here is a simple example:
===========================================
Example6.tpl
===========================================
<body>
This will output an array:<br>
{foreach from= $newsArray item=newsid}
News ID: {$newsID}<br>
News content: {$newsTitle}<br>{Foreachelse}
Sorry, there is no news output in the database!
{/foreach}
</body>
==========================================
example6.php
==========================================

<?php
/*********************************************
*
* File name: example6.php
* Function: show Instance program 2
*
* Author: Big bro
* Email: [Email protected]
*
*********************************************/
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" = "1th 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 located under./templates
$smarty->display ("Example6.tpl");
?>
=================================================
example6.php output File
=================================================
Examples of <body>
This will output an array:<br>
News ID:1<br>
News content: 1th News <br>News ID:2<br>
News content: 2nd News <br>News ID:3<br>
News content: 3rd News <br>News ID:4<br>
News content: 4th News <br>News ID:5<br>
News content: 5th News <br>News ID:6<br>
News content: 6th News <br></body>
foreach can also use Foreachelse to match, using Foreachelse to represent the action to be performed by the program when the array passed to the foreach is null, see
Description of the manual.
2. Section:
The section is generated to solve the problem of foreach, as with foreach, it is used to design the loop block within the template, it is more complex, can greatly program to meet the needs of the program, the
In the program I am accustomed to using it instead of using foreach, the basic prototype is:
{section name = name loop = $varName [, start = $start, step = $step, max = $max, show = True]}
The name of the name:section, without adding $
$loop: The variable to be looped, the variable is to be manipulated in the program using assign.
$start: Start loop subscript, loop subscript default starting from 0
$step: The increment of the mark at the time of each cycle
$max: Maximum cycle subscript
$show: Boolean type that determines whether to display this block, by default true
Here's a noun to explain:
Circular subscript: The actual English name of the index, is the meaning of indexing, here I translated it into "subscript", mainly for good understanding. It indicates when the loop block is displayed when the
Before the cyclic index, the default starting from 0, affected by $start, if $start is set to 5, it will also count from 5, in the template design section we used it, this is the current
A property of {section}, called Smarty.section.sectionName.index, where sectionname refers to the name attribute in the function prototype.
{section} blocks have property values, respectively:
1. Index: the "loop subscript" we introduced above, the default is 0
2. Index_prev: The previous value of the current subscript, the default is-1
3. Index_next: The next value of the current subscript, which defaults to 1
4. First: Whether it is a second cycle
5. Last: Is the final loop
6. Iteration: Number of cycles
7. RowNum: The current line number, another alias for iteration
8. Loop: The last loop number, the number of cycles that can be used to count sections after a section block
9. Total: Number of cycles that can be used to count cycles after a section block
Show: In the declaration of a function, it is used to determine whether the section is displayed
Their specific properties you can refer to the manual, in the program can be flexible use of its properties, template Part I have used the Index property, you can go back to look.
Similarly, {section} can also be used with {Sectionelse}, which is used to represent the processing of a template when an incoming array variable is empty.
Let's take the example above using {section} instead of {foreach} to implement the present-like functionality, and note that in this example I'll only use {foreach} in the TPL template
{section} to implement, there are no changes in PHP program files, and the {sectionelse} processing block is added:
===========================================
Example7.tpl
===========================================
<body>
This will output an array:<br>
{section Name=loop loop= $News}
News ID: {$News [loop].newsid}<br>
News title: {$News [loop].newstitle}<br>{Sectionelse}
Sorry, there is no news input!
{/section}
</body>

==========================================
example6.php
==========================================

<?php
/*********************************************
*
* File name: example7.php
* Function: show Instance program 2
*
* Author: Big bro
* Email: [Email protected]
*
*********************************************/
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" = "1th 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 located under./templates
$smarty->display ("Example6.tpl");
?>
=================================================
example7.php output File
=================================================
Examples of <body>
This will output an array:<br>
News ID:1<br>
News content: 1th News <br>News ID:2<br>
News content: 2nd News <br>News ID:3<br>
News content: 3rd News <br>News ID:4<br>
News content: 4th News <br>News ID:5<br>
News content: 5th News <br>News ID:6<br>
News content: 6th News <br></body>
The {section} block here feels a bit awkward about how the variable is named, but it doesn't matter, just remember that the template variable is used:
$loopName [Name].var This mode, Loopname is the variable name given at loop, [name] is the string given by name. After you set the program array to
The subscript name corresponding to the value is OK.

Well, smarty Study Guide---The programming chapter is written here, for the general application, this knowledge is sufficient, other advanced techniques please refer to the manual example

Go PHP template Smarty Simple Getting Started tutorial

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.