Template engine smarty working principle and use example _ php template

Source: Internet
Author: User
Tags php template
Smarty is a PHP template engine written using PHP. It provides the separation of logic and external content. In short, it aims to separate PHP programmers from the artist, the programmer used to change the logic content of the program does not affect the page design of the artist. the artist re-modifies the page template engine to merge the template file and data content, convenience for website development is conducive to code separation and maintenance. it is best to know the working principle of a template so as to realize one-way communication.

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

The code is as follows:
Array ([id] => 1, ['title'] => "title ",...);

Our template requires several corresponding tags, such

The code is as follows:
{$ Title}

{$ Content}


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

The 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

The 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:

The code is as follows:


  • 1111

  • 222

  • 333

  • 4444


If this is what we want to output

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

The 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

The code is as follows:
{Section name = name of the loop = name of the data volume}
...
{/Section}


{Section name = I loop = $ list}

  • {$ List [I]. title}

  • {/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:

    The code is as follows:
    {Foreach key = index item = value from = value assignment variable}

    {$ Key }:{ $ item}

    {/Foreach}

    {Foreach item = v from = $ list}

  • {$ V. title}
  • {/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:

    The 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

    The 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 replace the line feed in the output content
    To display the corresponding information on the page, we can use the variable regulator that comes with smarty. the format is as follows:

    The code is as follows:
    {Variable to be output | regulator name: parameter}

    For example, when the content is displayed, all line breaks are displayed
    You only need to write the following code:

    The code is as follows:
    {$ Content | nl2br}

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

    The 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

    The code is as follows:
    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.