Smarty Half-hour Quick start tutorial

Source: Internet
Author: User
Tags smarty template

From: http://www.chinaz.com/program/2010/0224/107006.shtml

One: The programming part of Smarty :

In the Smarty template Design section I simply put Smarty in the template of some common settings to do a simple introduction, this section mainly to introduce how to start our program design in Smarty. Download the Smarty file and put it on your site.
index.php PHP Code:

<?php
/**
*
* @version $Id: index.php
* @package
* @author www.php100.com
* @action Show Instance Program
*/
Include_once ("./smarty/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
$smarty->cache ("./cache"); Cache Directory
$smarty->cache_lifetime = 0; Cache time
$smarty->caching = true; Cache mode

$smarty->left_delimiter = "{#";
$smarty->right_delimiter = "#}";
$smarty->assign ("name", "Zaocha"); Make template variable substitution
$smarty->display ("index.htm"); Compile and display the index.htm template located under./templates
?>

II: Explain the Smarty procedure

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, but from the procedural style, 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, it is a directory, in the absence of this sentence, smarty the default template path is the templates directory of the current directory, the actual writing process, we will write this sentence, this is a good program 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 the directory where it compiles templates, note that if the site is located on a Linux server, make sure

The directory defined in Teamplates_c has a writable and readable permission, and by default its compilation directory is the Templates_c of the current directory, and for the same reason we write it explicitly.

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 definitions in <script>,script in the template, we will inevitably use {}, although it has its own solution, but it is customary for us to redefine it

For "{#" and "#}" or "<!--{" and "}-->" or other glyphs, note that if the left and right delimiters are defined here, in the template file corresponding to each variable to use the same as the definition of the symbol, for example, here is designated as "<{" and "}>", The HTM template should also be

The corresponding {$name} becomes <{$name}>, so that the program can correctly find the template variable.

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. By default, the cache directory under the current directory, equivalent to the Templates_c directory, is in the Linux system

We want to make sure it's 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 its value is-1, it means that the established cache never expires, and 0 indicates that each time the program executes

The deposit is always re-established. 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, means that the template is not cached, 1: Indicates that Smarty will use the currently defined cache_lifetime to decide whether to end Cache;2: represents

Smarty will use the value Cache_lifetime when the cache is built. It is customary to use true and false to indicate whether to cache.

: $smarty->assign ("name", "Zaocha"):

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, and its second prototype is assign (mixed Var), We want to explain in detail in the following example the use of this member function, assign is one of the core functions of smarty, all the substitution of the template variable to use it.

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 add the path, as long as the use of a file name, it is the path we have in $smarty->templates (string path) has been defined.

After the execution of the program we can open the current directory of the Templates_c and the cache directory, we will find a few more than a few percent of the directory, these directories are smarty compilation and cache directory, it is automatically generated by the program, do not directly modify these generated files.

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.

Three: Template description

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 are very close to the Smarty programming part, 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 empty, here is a simple example:

Template file: example.htm

foreach outputs a "two-dimensional associative array" of data:

{#foreach item=new from= $news #}

News ID: {# $new. id#}

News content: {# $new. title#}

{#foreachelse #}

There is no news output in the database!

{#/foreach#}

{foreach from= $newsArray item=newsid}

News ID: {$newsID}

News content: {$newsTitle}

{Foreachelse}

Sorry, there is no news output in the database!

{/foreach}

This is a bug that does not show the data, this article has made corrections.

Program Files: example.php

<?
/*********************************************
*
* File name: example.php
* Function: show Instance program 2
*********************************************/

Include_once ("./smarty/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");

This is a two-dimensional associative array

$smarty->assign ("Newsarray", $array);

Compile and display the index.htm template located under./templates

$smarty->display ("example.htm");

?>

Input Result: example.php

This will output an array:

Press ID: 1

News content: Article 1th News

Press ID: 2

News content: Article 2nd News

Press ID: 3

News content: Article 3rd News

Press ID: 4

News content: Article 4th News

Press ID: 5

News content: Article 5th News

Press ID: 6

News content: Article 6th News

foreach can also be matched with Foreachelse, using Foreachelse to indicate what the program will do when the array passed to the foreach is null, refer to the manual for instructions on how to use it.

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 satisfy the program needs, so in the program I used to use 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 represents the current cyclic index when the loop block is displayed, the default starting from 0, affected by $start, and if $start is set to 5, it will also count from 5, which we have used in the template Design section, which is a property of the current {section}. This is 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, note that in this example I will only implement {foreach} in the TPL template with {section}, without any changes in the PHP program file, plus { Sectionelse} processing Block:

Example.tpl

This will output an array:

{section Name=loop loop= $News}
News ID: {$News [Loop].newsid}
News title: {$News [Loop].newstitle}
{Sectionelse}
Sorry, there is no news input!
{/section}

example.php

<?
/*********************************************

*

* File name: example7.php

* Function: show Instance program 2

*********************************************/

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 ("Example.tpl");

?>

example.php output File

This will output an array:

Press ID: 1

News content: Article 1th News

Press ID: 2

News content: Article 2nd News

Press ID: 3

News content: Article 3rd News

Press ID: 4

News content: Article 4th News

Press ID: 5

News content: Article 5th News

Press ID: 6

News content: Article 6th News

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 is OK, Loopname is the variable name given at loop, [name] is the string given at name, and the following is for you to set the subscript name in the program array to correspond to the value.

Well, Smarty Study Guide---Programming chapter is written here, for the general application, this knowledge is sufficient, other advanced techniques please refer to the manual examples, the next section will talk about Smarty in the actual application of the example, will be the PHP built-in MySQL statements, respectively, DB Class in Phplib, the DB class in adodb,pear to explain the implementation of each class library in the same example respectively

Smarty Half-hour quick start tutorial (GO)

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.