How the template engine Smarty works and uses the sample _php tutorial

Source: Internet
Author: User
The template engine is a program for merging template files and data content so that Web development facilitates code separation and maintenance, and knowing that a template best knows how it works to achieve a wantong.

Template files are generally HTML XML JS and other types of files, if you do not use the template engine to display the data on the page, we need to output HTML in PHP, and using a template just give the data to the template engine program, and then tell it which template file to use, Nature will combine the data and the page to return or output later, the template has at least the following functions 1. The ability to 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, the developer will be the function to some extent encapsulated, encapsulated into a class, instantiated to get an object, namely the template engine object, an object has its properties and methods, Smarty object properties and methods found in the Smarty manual, First of all, say the method, assign the method of submitting the data to the template. There are no separate methods for specifying template files that have been merged into the output method, the output method has two display direct output fetch return the merged HTML code, for the output we mainly use assign because we display the data is often a multiplicity, may be a quantity, It may be an array or a multidimensional array, in different situations should be how to correctly submit to Smarty is a problem, how to display after the submission is also a problem, Smarty engine uses the interpretation method is to first convert the HTML file to php file, and then in the value of the various quantities, and execute this php file, corresponding to different data formats, it has a fixed writing style, we need to use this notation in the template file to make the corresponding tag, smarty default template tag is a pair of {}, such as {$a} This tag is equivalent to the echo $a; In PHP we need to have a corresponding assignment process, $smarty->assign ("A", "value"); If we have multiple assignments, it would be cumbersome to write each one, Smarty for us, for example, we read an article from the database, To display the content of the page with the title content of the author time, the data structure is generally like this

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

Our template needs to have several corresponding tags, such as

Copy the Code code as follows:

{$title}


{$content}

Assignment is too cumbersome, the Assign method supports array direct assignment, $rows = The data read from the database,

$smarty->assign ($rows); Smarty will take the data index automatically one by one assignment, but this time in order to avoid the collision of variables, we would like to be directly in the array form of assignment, such as

Copy the Code code as follows:
$rows = The data read from the database,
$smarty->assign ("Rows", $rows);

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

Copy the Code code as follows:
echo $rows [' title ']

Each template has its corresponding writing rules, next if you want to display a list of articles, if MySQL returned to US 10 data, 10 data to be displayed, and their index must be exactly the same, according to programming ideas to know the results of the process, the assumption is shown as follows

Copy the Code code as follows:


    • 1111

    • 222

    • 333

    • 4444


If that's what we want the output to look like

First of all, this is a number of arrays, of course,

Copy the Code code as follows:
$list =array ();
while ($rows = data) {
$list []= $rows;
}
$smarty->assign ("list", $list);

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

Section tag format

Copy the Code code as follows:
{section name= the name of this cycle loop= the data volume name}
...
{/section}


{section name=i loop= $list}

  • {$list [I].title}

  • {/section}

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

    Another way to do this is to foreach with the following syntax:

    Copy the Code code as follows:
    {foreach key= index item= value from= assignment variable}

    {$key}:{$item}

    {/foreach}

    {foreach Item=v from= $list}

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

    Loop list variable Each amount is assigned to V, and then from the variable v to specify the index to display, in addition to the loop tag, it gives us some common syntax tags, such as include files, conditional judgment, we know that HTML can not contain files, such as the page header, but Smarty provides { Include}, you can include files like PHP, such as {include file= "file path"} This tag format is fixed, and the path must be specified in the template engine path, and the syntax of the conditional judgment is the same as PHP is the IF condition judgment, the syntax is as follows

    Copy the Code code as follows:
    {if variable = = value or amount}
    The value to display when True
    {Else}
    Is the value shown for false
    {/if}

    It is also possible not to write else only when the content is true, for example, a common case is that there is a login on the Web page before the login display is the user information, assuming a quantity has been assigned to the template such as $username user login This amount there is a user name is not logged this amount is empty, We can write that.

    Copy the Code code as follows:
    {if $username! = ""}
    Welcome {$username}
    {Else}
    Please login first
    {/if}

    All we have to do is get this variable ready in PHP and assign it to smarty in addition to the tag's own reference manual,

    The second is the variable regulator, many times we get data from the database, we have to small processing to output, such as the date format, only display the month and day can again as the output of the contents of the line to be replaced
    In order to display the corresponding appearance on the page, this time we can use Smarty's own variable adjuster, the format is as follows

    Copy the Code code as follows:
    {Variable to Output | adjuster name: parameter}

    If the Content section displays all the line breaks as
    Just use the following notation

    Copy the Code code as follows:
    {$content |NL2BR}

    Date formatting can be used date_format such as the manual

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

    We can work with PHP and then assign.

    Write down the configuration below

    Copy the Code code 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 Catalogs
    $smarty->settemplatedir (ROOT. ' templates/')
    ->setcompiledir (ROOT. ' Templates_c ')
    ->setpluginsdir (ROOT. ' plugins/')
    ->setcachedir (ROOT. ' cache/')
    ->setconfigdir (ROOT. ' configs/');
    $smarty->caching = false;//Whether the cache is turned on
    $smarty->left_delimiter = ' <{';//set to prevent conflicts with JS CSS and so on
    $smarty->right_delimiter = '}> ';
    ?>

    http://www.bkjia.com/PHPjc/776460.html www.bkjia.com true http://www.bkjia.com/PHPjc/776460.html techarticle template engine is a program used to combine template files and data content, so that Web development facilitates code separation and maintenance, knowing that a template best knows how it works so ...

  • 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.