Home  >  Article  >  Backend Development  >  Template engine smarty working principle and usage examples_PHP tutorial

Template engine smarty working principle and usage examples_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:29:26936browse

Template engine is a program used to merge template files and data content together, which facilitates website development and facilitates code separation and maintenance. To understand a template, it is best to know how it works, so that it can be used for everything.

Template files are generally HTML xml js and other types of files. If we don’t use a template engine and want to display the data on the web page, we need to output HTML in php. But when using templates, we only need to hand the data to the template engine program. Then tell it which template file to use, and it will naturally combine the data with the page and then return or output it. The template has at least the following functions: 1. The function of providing data to the template engine. 2. Specify the function of the template. 3. The function of outputting results. Generally speaking, in order to facilitate programmers to use the template engine, developers will encapsulate its functions to a certain extent and encapsulate it into a class. After instantiation, an object is obtained, that is, the template engine object. An object has its properties and methods. , the properties and methods of the smarty object can be found in the smarty manual. First, let’s talk about its methods, assign method to submit data to the template. There is no separate method for specifying template files and has been merged into the output method. There are two output methods: display, direct output, and fetch, which returns the merged HTML code. For output, we mainly use assign because the data we display is often diverse. Sexual, it may be a quantity, it may be an array quantity or it may be a multi-dimensional array. How to correctly submit it to smarty under different circumstances is a problem. How to display it after submission is also a problem. The interpretation method used by the smarty engine is First convert the HTML file into a php file, then assign various values, and execute this php file, which corresponds to different data formats. It has a fixed writing method, which requires us to use this writing method to make corresponding marks on the template file. , the template tags used by smarty by default are a pair of {}, for example, {$a} is equivalent to echo $a; in php, we need to have a corresponding assignment process, $smarty->assign("a", "value"); If we have multiple quantities to assign values ​​to, it will be very troublesome to write them one by one. Smarty takes this into consideration for us. For example, when we read an article from the database, the content to be displayed on the page has the title, content, and author. Time, the data structure is roughly like this

Copy code The code is as follows:

array([id]=>1,['title']=> "Title",…);

Our template needs to have several corresponding tags, such as

Copy code The code is as follows:

{$title}


< div>{$content}

Assigning values ​​one by one is too troublesome. The assign method supports direct assignment of arrays. $rows = data read from the database.

$smarty->assign($rows); smarty will take the data index and automatically assign values ​​one by one. However, in order to avoid variable conflicts at this time, we hope to assign values ​​directly in the form of an array, such as

Copy code The code is as follows:

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

If our tag in the template is {$rows} at this time, we can only see the array when outputting. Just like the direct echo array in php, the specific amount output in php is echo $rows['title'];smarty The specified symbol is a period, {$rows.title}, in this way similar to

Copy code The code is as follows:

echo $rows['title']

Each template has its corresponding writing rules. If you want to display a list of articles next, assuming that mysql returns 10 pieces of data to us, all 10 pieces of data must be displayed, and their indexes must be exactly the same. , know the result calculation process according to the programming idea, the assumption is as follows

Copy code The code is as follows:


  • 1111

  • 222

  • 333

  • 4444


If this is what we want the output to look like

First of all, these are multiple quantities, of course they use arrays,

Copy code The code is as follows:

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

First put the data into an array and then give it to smarty all at once. In this way, the list variable contains a two-dimensional array. If we get such a two-dimensional array, it is best to display all the values ​​in it. The method is to loop output. Similarly, smarty provides us with loop tags, section and foreach

section tag format

Copy the code The code is as follows:

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


{section name=i loop=$list}

  • {$list[i].title}

  • {/section}

    The above code looks very much like a for loop, but the i here is not the $i in the for loop. It is just the name of this loop. The writing method $list [loop name] can get an amount from the array each time, as just now That said, $list is a two-dimensional array, and $list[i] still gets an array.

    Another way to write it is foreach. Its syntax is as follows:

    Copy code The code is as follows:

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

    {$key}:{$item}

    {/foreach}

    {foreach item=v from=$list}

  • {$v.title}
  • {/foreach}

    Assign each value of the loop list variable to v, and then specify the index to be displayed from the variable v. In addition to loop tags, it also provides us with some commonly used syntax tags, such as included files, conditional judgments, we We know that HTML cannot include files, such as web page headers, but smarty provides the {include} tag, which can include files like PHP, such as {include file="file path"}. The format of this tag is fixed, and the path must be in Under the path specified by the template engine, the syntax for conditional judgment is the same as if conditional judgment like PHP. The syntax is as follows

    Copy code The code is as follows:

    {if variable==value or amount}
    The value displayed when it is true
    {else}
    False is the displayed value
    {/if}

    You can also not write else and only display the content when it is true. For example, a common situation is that there is a login port on the web page. Before logging in, the form is displayed. After logging in, the user information is displayed. Assume that a quantity has been assigned to the template. For example, if the user logs in $username, the amount will contain the username. If the user is not logged in, the amount will be empty. We can write like this

    Copy code The code is as follows:

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

    We only need to prepare this variable in php and assign it to smarty. In addition to these tags, we can refer to the manual for other tags by ourselves,

    The second is the variable regulator. Many times, the data we get from the database needs to be slightly processed before outputting it. For example, the date format only displays the year, month and day, or line breaks in the output content. You need to change it to
    to display the corresponding appearance on the page. At this time, we can use the variable regulator that comes with smarty. The format is as follows

    Copy code The code is as follows:

    {Variable to be output | Regulator name: parameter}

    If the content part displays all line breaks as
    , it only needs to be written as follows

    Copy code The code is as follows:

    {$content|nl2br}

    To format dates, you can use date_format, for example, in the manual

    Copy code 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

    If it doesn’t work, we can use php to handle it and then assign the value.

    Write the configuration below

    Copy code The code is as follows:

    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 directories
    $ smarty ->setTemplateDir(ROOT.'templates/')
    ->setCompileDir(ROOT.'templates_c')
    ->setPluginsDir(ROOT.'plugins/')
    ->setCacheDir( ROOT.'cache/')
    ->setConfigDir(ROOT.'configs/');
    $smarty->caching = false;//Whether to enable caching
    $smarty->left_delimiter = '<{';//Set the left and right to prevent conflicts with js css, etc.
    $smarty->right_delimiter = '}>';
    ?>

    www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/776460.htmlTechArticleThe template engine is a program used to merge template files and data content together, which facilitates website development and facilitates code separation. and maintenance, to understand a template it is best to know how it works in order to...
    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Previous article:2 ways to convert a two-dimensional array to a one-dimensional array_PHP tutorialNext article:2 ways to convert a two-dimensional array to a one-dimensional array_PHP tutorial

    Related articles

    See more