Template engine working principle and example

Source: Internet
Author: User

The template engine is a program used to merge template files and data content. It facilitates code Separation and Maintenance for website development. It is best to know how a template works, so that you can easily implement a one-way connection.

Template files are generally HTML, xml, js, and other types of files. If you do not need a template engine to display data on a webpage, You need to output HTML in php, to use a template, you only need to hand over the data to the template engine program and then tell it which template file to use. Naturally, the data will be returned or output after being combined with the page, the template must have at least one of the following functions. provides data to the template engine. 2. Specify the template function. 3. output result function. Generally, to make it easier for programmers to use the template engine, developers will encapsulate its functions into a class to a certain extent, and get an object after instantiation, that is, the template engine object, an object has its attributes and methods. The attributes and methods of the smarty object are searched in the smarty manual. First, let's talk about the method. assign submits the data to the template. Methods without specifying template files have been merged into the output method. The output method has two display methods that directly output fetch and return the merged HTML code, for the output, we mainly use assign. Because the data we display is often diverse, it may be a volume, it may be an array or a multi-dimensional array, the correct submission to smarty is a problem under different circumstances, and the corresponding display after submission is also a problem. The smarty engine uses the Explanation Method to convert the HTML file into a PHP file first, then, assign values to different quantities and execute this PHP file, which corresponds to different data formats. It has a set of fixed writing methods. We need to use this writing method to mark the template file, the default template tag used by smarty is a pair of {}. For example, the tag {$ a} is equivalent to echo $ a. in php, We need to assign a value, $ smarty-> assign ("a", "value"); if we assign values to multiple quantities, it is very troublesome to write them one by one. smarty considers this for us, for example, if we read an article from the database and want to display the content on the page with the title content author time, the data structure is generally like this

Copy codeThe Code is as follows:
Array ([id] => 1, ['title'] => "title ",...);

Our template requires several corresponding tags, such

Copy codeThe Code is as follows:
<H1 >{$ title} <Div >{$ content} </div>

Assigning values one by one is too troublesome. The assign Method supports direct assigning values to arrays. $ rows = reads data from the database,

$ Smarty-> assign ($ rows); smarty will take the data index and assign values one by one automatically. But in this case, we want to assign values directly in the form of arrays to avoid variable conflicts. For example

Copy codeThe Code is as follows:
$ Rows = data read from the database,
$ Smarty-> assign ("rows", $ rows );

If the tag of the template is {$ rows} at this time, we can only see the array as the echo array in php, the actual output volume in php is echo $ rows ['title']; The symbol specified by smarty is a point number, {$ rows. title}. This method is similar

Copy codeThe Code is as follows:
Echo $ rows ['title']

Each template has its own writing rules. If you want to display a list of articles next, suppose mysql returns 10 data records and 10 data records, in addition, their indexes must be exactly the same. According to the programming idea, the results are obtained. The following is shown:

Copy codeThe Code is as follows:
<Ul>
<Li> 1111 </li>
<Li> 222 </li>
<Li> 333 </li>
<Li> 4444 </li>
</Ul>

If this is what we want to output

First, this is an array of multiple quantities, of course,

Copy codeThe Code is as follows:
$ List = array ();
While ($ rows = data ){
$ List [] = $ rows;
}
$ Smarty-> assign ("list", $ list );

Put the data in an array before handing it over to smarty. In this way, the list variable is a two-dimensional array. If we get such a two-dimensional array, We need to display all the values in it, the best method is loop output. Similarly, smarty provides the mark, section, and foreach for loop.

Section tag format

Copy codeThe Code is as follows:
{Section name = name of the loop = name of the data volume}
...
{/Section}


{Section name = I loop = $ list}
<Li >{$ list [I]. title} </li>
{/Section}

The above code looks like a for loop, but here I is not the $ I in the for loop, just the name of this loop, $ list [loop name] can get a number from the array each time. As mentioned earlier, $ list is a two-dimensional array, and $ list [I] is an array.

The syntax of foreach is as follows:

Copy codeThe Code is as follows:
{Foreach key = index item = value from = value assignment variable}

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

{/Foreach}

{Foreach item = v from = $ list}

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

{/Foreach}

Every volume of the cyclic list variable is assigned to v, and then the index to be displayed is specified from v. In addition to the cyclic tag, it also provides some common syntax tags, for example, if a file is included and the condition is determined, we know that HTML cannot contain files, such as the webpage header. However, smarty provides {include} tags that can contain files like php, for example, the tag format {include file = "file path"} is fixed and must be in the path specified by the template engine, the condition judgment syntax is the if condition judgment syntax like php. The syntax is as follows:

Copy codeThe Code is as follows:
{If variable = value or amount}
Value displayed when the value is true
{Else}
False is the displayed Value
{/If}

You can also ignore the content displayed only when else is true. For example, there is a logon port on the webpage that displays user information after form logon, assume that a volume has been assigned to the template. For example, if $ username is used to log on to the template, the user name is empty. You can write

Copy codeThe Code is as follows:
{If $ username! = ""}
Welcome {$ username}
{Else}
Log on first
{/If}

We only need to prepare this variable in php and assign it to smarty. We can refer to the Manual for additional markup,

The second step is the variable regulator. Most of the time the data we get from the database is output only after small processing, such as the date format, display only the year, month, and day, and change the line feed in the output content to <br/> to display the corresponding display on the page. At this time, we can use the variable regulator that comes with smarty, in the following format:

Copy codeThe Code is as follows:
{Variable to be output | regulator name: parameter}

If the content section displays all line breaks as <br/>, you only need to write the following statement:

Copy codeThe Code is as follows:
{$ Content | nl2br}

You can use date_format for date formatting, for example, in the manual.

Copy codeThe Code is 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

We can use php to handle the problem and then assign values.

Write the configuration below

Copy codeThe Code is as follows:
<? Php
Define ("ROOT", str_replace ('\', '/', dirname (_ FILE _). '/'); // define the ROOT path
// Load the smarty class
Require ROOT. 'lib/smarty. class. php ';
$ Samrty = new smarty (); // instantiate a smarty class
// Configure various directories
$ Smarty-> setTemplateDir (ROOT. 'templates /')
-> SetCompileDir (ROOT. 'templates _ C ')
-> SetPluginsDir (ROOT. 'ins INS /')
-> SetCacheDir (ROOT. 'cache /')
-> SetConfigDir (ROOT. 'configs /');
$ Smarty-> caching = false; // whether to enable Cache
$ Smarty-> left_delimiter = '<{'; // sets the left and right sides to prevent conflicts with js css.
$ 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.