Smarty Half Hour Quick Start Tutorial _php instance

Source: Internet
Author: User
Tags manual function definition function prototype php language mixed readable smarty template

This article describes the Smarty Quick Start method, allowing readers to quickly grasp the use of smarty within half an hour. Share to everyone for your reference. The implementation methods are as follows:

The programming part of Smarty:

In the Smarty template Design section I simply put the smarty in the template some common settings do a simple introduction, this section mainly to introduce how to start our program in the Smarty. Download the Smarty file and put it in your site.

The index.php code is as follows:

Copy Code code as follows:
<?php
/**
*
* @version $Id: index.php
* @package
* @author www.jb51.net
* @action Display Instance Program
*/
Include_once ("./smarty/smarty.class.php"); Contains Smarty class files

$smarty = new Smarty (); Establish a Smarty instance object $smarty
$smarty->templates ("./templates"); Set up template catalogs
$smarty->templates_c ("./templates_c"); Setting up the compilation directory
$smarty->cache ("./cache"); Cache Directory
$smarty->cache_lifetime = 0; Cache time
$smarty->caching = true; Caching 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 that is located under./templates
?>


ii. Procedures for interpreting Smarty

We can see that the Smarty part of the program is actually a set of code that conforms to the PHP language specification, which we explain in turn:

1:/**/statement:

The included section is a program header comment. The main content should be the role of the program, copyright and the author and writing time to do a simple introduction, which is not required in the smarty, but from the style of the program, this is a good style.

2:include_once statement:

It will be installed to the Web site Smarty file included in 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 the absence of this sentence, smarty the default template path for the current directory templates directory, in fact, when writing a program, we want to write this sentence, this is a good program style.

5: $smarty->templates_c (""):

This sentence indicates the directory at compile time for the $smarty object. In the template design article we already know that Smarty is a compiled template language, and this directory is the directory where it compiles templates, and note that if the site is on a Linux server, make sure

The directory defined in Teamplates_c has writable readable permissions, and by default its compiled directory is the Templates_c of the current directory, and for the same reason we write it clearly.

6: $smarty->left_delimiter with $smarty->right_delimiter:

Indicates the left and right delimiters when looking for template variables. By default, "{" and "}", but in practice because we want to use the function definition in <script>,script in the template will inevitably use {}, although it has its own solution, but it is customary for us to redefine it

To "{#" and "#}" or "<!--{" and "}-->" or other markers, note that if you define the left and right delimiters here, in the template file, you want each variable to use the same symbol as the definition, such as "<{" and "}>" here, The HTM template should also

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

7: $smarty->cache ("./cache"):

Tells Smarty the location of the template file cache for output. We know that the biggest advantage of smarty is that it can be cached, and here is the directory where the cache is set. By default, the cache directory under the current directory, similar to the Templates_c directory, 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 for the calculation of the cache to be valid. When the first cache time expires, the cache is rebuilt when the Smarty caching variable is set to True. When its value is-1 indicates that the established cache never expires, and 0 indicates that the program is slow at every execution

The deposit is always being built again. 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. It can take 3 values, 0:smarty the default value, and indicates that the template is not cached; 1: Indicates that Smarty will use the currently defined cache_lifetime to decide whether to end Cache;2:

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

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

The prototype of the number is assign (string varname, mixed Var), varname the template variable used in the template, var indicates the variable name to replace the template variable, and 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, and all substitutions to template variables are to be used.

One: $smarty->display ("Index.tpl"):

This function is displayed as display (string varname), which acts as a template. Simply put, it shows the parsed template, where the template file does not need a path, as long as a filename is available, and 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 cache directory, you will find in the bottom of a number of% of the directory, these directories are smarty compiled and cached directories, it is automatically generated by the program, do not directly modify these generated files.

I've simply introduced some of the most common basic elements in the Smarty program, and in the example below you can see that they will be used more than once.

Iii. Description of the template

Next, we introduce a section loop block and a foreach loop block, which should be part of the template, but because they are the essence of the smarty and are very closely related to the Smarty programming part, let's take a look at it separately.

1:foreach: For a simple array of loops, it is a selective section loop, which is defined in the following format:

Copy Code code as follows:
{foreach from= $array item=array_id}
{Foreachelse}
{/foreach}

Where the from indicates the array variable to loop, the item is the name of the variable to loop, and the number of loops is determined by the number of array variables specified from. {Foreachelse} is used when the array passed over in the program is empty, the following is a simple example:

Template file:

The Example.htm page is as follows:

Copy Code code as follows:
foreach outputs a "two-dimensional associative array" of data:

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

News number: {# $new. id#}

News content: {# $new. title#}

{#foreachelse #}
There is no news output in the database!

{#/foreach#}

{foreach from= $newsArray item=newsid}
News number: {$newsID}
News content: {$newsTitle}
{Foreachelse}
Sorry, there is no news output in the database!

{/foreach}


This is a mistake to not display the data that this article made corrections.

Program Files: example.php as follows:

Copy Code code as follows:
<?php
/*********************************************
*
* FileName: example.php
* Role: 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 piece of News");
$array [] = Array ("NewsID" =>2, "Newstitle" => "2nd piece of News");
$array [] = Array ("NewsID" =>3, "Newstitle" => "3rd piece of News");
$array [] = Array ("NewsID" =>4, "Newstitle" => "4th piece of News");
$array [] = Array ("NewsID" =>5, "Newstitle" => "5th piece of News");
$array [] = Array ("NewsID" =>6, "Newstitle" => "6th piece of News");
This is a two-dimensional associative array
$smarty->assign ("Newsarray", $array);
Compile and display the index.htm template that is located under./templates
$smarty->display ("example.htm");
?>

Input result: example.php output is as follows:

Copy Code code as follows:
This will output an array:

Press Number: 1

News content: 1th article News

Press Number: 2

News content: 2nd article News

Press Number: 3

News content: 3rd article News

Press Number: 4

News content: 4th article News

Press Number: 5

News content: 5th article News

Press Number: 6

News content: 6th article News

foreach can also be matched with Foreachelse, using Foreachelse to indicate what the program will do when the array passed to foreach is null, and refer to the instructions in the manual.

2. Section:

The section is created to solve the problem of foreach, like 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, so in the program I used to use it instead of foreach, the basic prototype is:

Copy Code code as follows:
{section name = name loop = $varName [, start = $start, step = $step, max = $max, show = True]}

The parameters are explained as follows:

The name of the name:section, do not add $

$loop: The variable to loop, in the program to use assign to manipulate the variable.

$start: Start loop subscript, loop subscript default starting from 0

$step: Increasing the number of marks per cycle

$max: Maximum cyclic subscript

$show: Boolean type that determines whether the block is displayed, and the default is True
Here's a noun to note:

Circular subscript: Actually its English name is index, it is the meaning of indexing, here I will translate it to "subscript", mainly for good understanding. It represents the current circular index at the time the loop block is displayed, the default starting from 0, is affected by $start, if the $start is set to 5, it will also count from 5, which we used in the template Design section, which is a property of the current {section}, The call is Smarty.section.sectionName.index, where sectionname refers to the name attribute in the function prototype.

{SECTION} block has property values, respectively:

1. Index: Above we introduce "circular subscript", the default is 0

2. Index_prev: The previous value of the current subscript, which defaults to-1

3. Index_next: The next value of the current subscript, the default is 1

4. First: Is the cycle

5. Last: whether the final loop

6. Iteration: Cycle times

7. RowNum: Current line number, another alias for iteration

8. Loop: The last loop number that can be used to count the number of loops in a section after a section block

9. Total: Cycle times, available after section block statistics cycle times

Show: In the declaration of a function, it is used to determine whether a section is displayed

Their specific properties you can refer to the manual, in the program can be flexible use of these properties, template Part I have used the Index property, we can go back to see.

Similarly, {section} can be used in conjunction with {Sectionelse} to represent the processing of a template when an incoming array variable is empty.

We put the example above using {section} to replace {foreach} to achieve the present-like function, note that in this example, I will only implement {foreach} in the TPL template with {section}, no changes in the PHP program file, plus { Sectionelse} processing Block:

The Example.tpl template file is as follows:

Copy Code code as follows:
This will output an array:

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

example.php files are as follows:

Copy Code code as follows:
<?php
/*********************************************

*

* FileName: example7.php

* Role: 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 piece of News");

$array [] = Array ("NewsID" =>2, "Newstitle" => "2nd piece of News");

$array [] = Array ("NewsID" =>3, "Newstitle" => "3rd piece of News");

$array [] = Array ("NewsID" =>4, "Newstitle" => "4th piece of News");

$array [] = Array ("NewsID" =>5, "Newstitle" => "5th piece of News");

$array [] = Array ("NewsID" =>6, "Newstitle" => "6th piece of News");

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

Compile and display the Index.tpl template that is located under./templates

$smarty->display ("Example.tpl");

?>


The example.php output file is as follows:

Copy Code code as follows:
This will output an array:

Press Number: 1

News content: 1th article News

Press Number: 2

News content: 2nd article News

Press Number: 3

News content: 3rd article News

Press Number: 4

News content: 4th article News

Press Number: 5

News content: 5th article News

Press Number: 6

News content: 6th article News


Here the {section} block is a bit awkward to name the variable, but it doesn't matter, you just have to remember that template variables are used:

$loopName [Name].var This pattern, loopname the variable name given at the loop, the string given at name (name). For you to set the subscript name in the program array that corresponds to the value.

Well, this article about Smarty Programming Learning Guide to write here, for the general application, this knowledge is enough, other advanced techniques, please refer to the manual examples, in addition to the relevant smarty in the actual application of the example, PHP built-in MySQL statement, The DB class in Phplib, the DB class in Adodb,pear, and so on. Interested friends can focus on the relevant content.

I hope this article will help you with your PHP program design.

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.