Template engine Smarty How it works and using the sample _php template

Source: Internet
Author: User

Template engine is used to combine template files and data content together, easy to develop web site development is conducive to code separation and maintenance, understand a template better know how it works, in order to achieve a wantong.

Template files are generally HTML XML JS type files, if not the template engine to display data on the Web page, we need to output HTML in PHP, and the use of templates as long as the data to the template engine program can then tell it with which template file, Nature will be the combination of data and pages returned or output, the template has at least the following features 1. Provide data to the template engine. 2. Specify the functionality of the template. 3. Function of output result. In general, in order to facilitate programmers to use the template engine, developers will be a certain degree of encapsulation of its functions, encapsulated into a class, instantiated to get an object, that is, the template engine object, an object has its properties and methods, Smarty object properties and methods found in the Smarty manual, First of all, the method is assign to submit the data to the template. No separate method for specifying template files has been merged into the output method, the output method has two display direct output fetch returns the merged good HTML code, for the output we mainly use assign because the data we display is often diverse, possibly a quantity, may be an array or multidimensional array, in different cases how to correctly submit to Smarty is a problem, how to submit the corresponding display is also a problem, Smarty engine to use the interpretation of the first HTML file into PHP file, and then in the assignment of various quantities, And the implementation of this PHP file, corresponding to different data formats, it has a fixed way of writing, we need to use this writing in the template file to do the corresponding tag, smarty default use of the template tag is a pair of {}, such as {$a} This tag is equivalent to the echo $a; In PHP we need to have the corresponding assignment process, $smarty->assign ("A", "value"), and if we have more than one quantity to assign, it would be troublesome to write it, Smarty for us, for example, we read an article from the database, To be displayed on the page content has the title Content author time, the data structure is generally this

Copy Code code as follows:

Array ([id]=>1,[' title ']=> ' heading ",...);

Our template needs to have several corresponding tags, such as

Copy Code code as follows:

<div>{$content}</div>

Assigning too much trouble, the Assign method supports array direct assignment, $rows = read from the database,

$smarty->assign ($rows); Smarty will take the data index automatically one by one assignment, but this time to avoid causing variable conflicts, we want to be directly in the form of an array assignment, for example

Copy Code code as follows:

$rows = The data read from the database,
$smarty->assign ("Rows", $rows);

If at this time we are in the template's tag is {$rows} that output, we can only see the array as direct echo array in PHP, the output in PHP is the echo $rows [' title '];smarty the symbol specified is a dot number, {$ Rows.title}, in this way is similar to

Copy Code code as follows:

echo $rows [' title ']

Each template has its corresponding writing rules, then if you want to display a list of articles, assuming that MySQL returned 10 data to us, 10 data will be displayed, and their index must be exactly the same, according to the programming idea of the results of the process, assuming that the following is shown

Copy Code code as follows:

<ul>
<li>1111</li>
<li>222</li>
<li>333</li>
<li>4444</li>
</ul>

If this is what we want the output to look like,

First of all, it's a number of quantities, of course, with arrays,

Copy Code code as follows:

$list =array ();
while ($rows = data) {
$list []= $rows;
}
$smarty->assign ("list", $list);

First put the data into an array and once again to smarty, so that the list variable is a two-dimensional array, if we get a two-dimensional array of such, to display all the values inside, the best way is to loop out the output, the same smarty for us to provide a circular tag, Section and foreach

Section tag format

Copy Code code as follows:

{section name= the name of this cycle loop= data volume name}
...
{/section}


{section name=i loop= $list}
<li>{$list [i].title}</li>
{/section}

The code above looks like a for loop, but here I'm not for loops inside the $i is just the name of the loop, $list [loop name] This notation can get a quantity from the array each time, as we just said, $list is a two-dimensional array, $list [i] gets an array.

Another way to do that is by foreach. The syntax is as follows:

Copy Code code as follows:

{foreach key= index item= value from= assignment variable}

{$key}:{$item}<br/>

{/foreach}

{foreach Item=v from= $list}

<li>{$v .title}</li>

{/foreach}

The loop list variable is assigned to V in each quantity, then specify the index to display from the variable V, in addition to the circular tag, it gives us some common syntax tags, such as include files, conditional judgments, we know that HTML cannot contain files, such as the head of a Web page, but Smarty provides { Include tags that can contain files like PHP, such as {include file= "file path"} This tag format is fixed, and this path must be in the path specified by the template engine, and the conditional judgment syntax is the same as if PHP is the IF condition, the syntax is as follows

Copy Code code as follows:

{if variable = = value or amount}
Value to display when True
{Else}
is the value displayed for false
{/if}

You can also not write anything else that is displayed when it is true. For example, a common situation is that there is a landing on the Web page before the login display is the form of user information is displayed, assuming that a quantity has been assigned to the template for example $username user login This amount of user name does not log in this amount is empty, We can write this.

Copy Code code as follows:

{if $username!= ""}
Welcome {$username}
{Else}
Please log in first
{/if}

All we have to do is prepare this variable in PHP and assign it to the Smarty to mark our own reference manual in addition to these tags,

The second is the variable regulator, many times we get data from the database, have to small processing to output, such as date format, only show the month and a day can again, such as the output of the content of the line to change <br/> in the page to show the corresponding appearance, This time we can use the Smarty with the variable regulator, the format is as follows

Copy Code code as follows:

{Variable to Output | adjuster name: parameter}

If the Content section in the display of all the line to show as <br/> Only need the following wording

Copy Code code as follows:

{$content |NL2BR}

The format of the date can be used date_format such as the manual

Copy Code code as follows:

index.php:

$smarty = new Smarty;
$smarty->assign (' Yesterday ', Strtotime ('-1 day '));
$smarty->display (' Index.tpl ');

INDEX.TPL:

{$smarty. Now|date_format}
{$smarty. Now|date_format: "%A,%B%e,%Y"}
{$smarty. Now|date_format: "%h:%m:%s"}
{$yesterday |date_format}
{$yesterday |date_format: "%A,%B%e,%Y"}
{$yesterday |date_format: "%h:%m:%s"}

OUTPUT:

Feb 6, 2001
Tuesday, February 6, 2001
14:33:00
Feb 5, 2001
Monday, February 5, 2001
14:33:00

It's not going to work. We can do it with PHP and then assign it.

Write the configuration below

Copy Code code as follows:

<?php
Define ("ROOT", str_replace (' \ \ ', '/', dirname (__file__)). ' /');//define Root Path
Load Smarty Class
Require ROOT. ' lib/smarty.class.php ';
$samrty = new Smarty ();//Instantiate a Smarty class
Configure various Catalogs
$smarty->settemplatedir (ROOT. ' templates/')
->setcompiledir (ROOT. ' Templates_c ')
->setpluginsdir (ROOT. ' plugins/')
->setcachedir (ROOT. ' cache/')
->setconfigdir (ROOT. ' configs/');
$smarty->caching = false;//whether to turn on caching
$smarty->left_delimiter = ' <{';//set to prevent and JS CSS and other conflicts
$smarty->right_delimiter = '}> ';
?>

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.