How Template Engine smarty works and examples of its use

  • 2021-06-28 11:52:37
  • OfStack

Template Engine is a program used to merge template files and data content. It is convenient for website development to facilitate code separation and maintenance. Knowing how a template works is a good way to achieve 10,000 passes.

Template file 1 is usually a file of type HTML xml js. If you don't use a template engine to display data on a web page, we need to output HTML in php. If you use a template, you can simply give the data to the template engine program and tell it which template file to use. The data and pages will naturally be combined and returned or output later.Templates have 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 outputting results.1 Generally speaking, in order to make it easier for programmers to use the template engine, developers will encapsulate its functions to a certain extent, encapsulate it into a class, and instantiate it to get an object, that is, a template engine object, an object with its properties and methods, smarty object's properties and methods are found in the smarty manual, first of all, its methods, assign method of submitting data to the template.There is no separate method to specify a template file that has been merged into the output method. The output method has two displays that directly output fetch to return the merged HTML code. For the output we mainly use assign because the data we display is often diverse, either a quantity, an array quantity, or a multidimensional array.How to correctly submit to smarty in different situations is a problem, and how to display it accordingly after submission is also a problem. The smarty engine uses the method of interpreting the HTML file by first converting it into an php file, then assigning various quantities and executing the php file, which corresponds to different data formats and has a fixed set of writing styles.We need to mark the template file in this way. By default, smarty uses a pair of {} template markers, such as {$a}, which is equivalent to echo $a.In php we need a corresponding assignment, $smarty- > assign ("a", "Value");If we have multiple quantities to assign, one would be cumbersome to write like this. smarty takes this into account for us. For example, we read an article from a database and the content to be displayed on the page has title content author time. The data structure is roughly the same


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

Our template needs to have several corresponding tags, such as


<h1>{$title}</h1>
<div>{$content}</div>

One assignment is too cumbersome. The assign method supports direct array assignment, $rows = data read from the database.

$smarty- > assign ($rows);smarty will automatically assign 11 to the data index, but at this point, to avoid variable conflicts, we want to assign it directly as an array, for example


$rows =  Data read from a database, 
$smarty->assign("rows",$rows);

If the label of the template is {$rows} at this time, we can only see array as direct echo array 1 in php, the specific output quantity in php is echo $rows['title'];The symbol specified by smarty is a dot, {$rows.title}, similar in this way


echo $rows['title']

Each template has its own writing rules. Next, if you want to show a list of articles, suppose mysql returned us 10 pieces of data, all 10 pieces of data will be displayed, and their indexes must be exactly the same. You know the result evaluation process according to your programming ideas, assuming the following is displayed


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

If this is what we want to output

First, of course, multiple quantities use arrays.


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

First put the data in an array and then have sex with smarty once, so 1 list variable is a 2-dimensional array. If we get a 2-dimensional array like this, the best way to show all the values is to cycle the output. smarty also gives us circular markers, section and foreach

section tag format


{section name= Name of this cycle  loop= Data quantifier name }
...
{/section}

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

The code above looks like an for loop, but here, i is not the name of $i inside the for loop. The notation $list [loop name] can get one quantity from the array at a time. As you just said, $list is a 2-dimensional array, $list [i] is an array or not.

Another way to write it is foreach whose syntax is as follows:


{foreach key= Indexes  item= value  from= Assignment variable }
{$key}:{$item}<br />
{/foreach}
{foreach  item=v from=$list}
<li>{$v.title}</li>
{/foreach}

Loop list variable assigns each variable to v, then specifies the index to be displayed from the variable v. In addition to the loop tag, it also provides us with some common syntax tags, such as include file, conditional judgment, we know that HTML cannot contain files, such as the header of a Web page, but smarty provides {include} tags.You can include files like php1, for example, {include file="File Path"} This tag format is fixed, and the path must be in the path specified by the template engine. The syntax of conditional judgment is if conditional judgment like php1, and the syntax is as follows


{if variable == Value or quantity }
 Value displayed when true 
{else}
 False is the displayed value 
{/if}

You can also skip writing what else only shows when it is true. For example, a common case is that there is a login on a web page that shows user information after a form login. Assuming that a quantity has been assigned to a template, for example, $username user login has a user name that is empty if there is no login, we can write this


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

We only need to prepare this variable for php and assign it to smarty to refer to the manual for the markers we have in addition to these.

Secondly, the variable adjuster. Most of the time, the data we get from the database needs little processing to be output. For example, the date format, which only shows the day, month and year, will be replaced by the new line in the output. < br / > In order to display the corresponding page, we can use smarty's own variable regulator at this time, in the following format


{ Variables to output | Adjuster Name: Parameters }

If the content section displays all the line breaks as < br / > Just write as follows


{$content|nl2br}

Date formatting can be done using date_format as in the manual


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

That's really not possible. We can use php to handle it before assigning it.

Write Configuration Below


<?php
define("ROOT",str_replace('\\','/',dirname(__FILE__)).'/');// Define Root Path 
// Load smarty class 
require ROOT.'lib/smarty.class.php';
$samrty = new smarty();// instantiation 1 individual 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 turn on caching 
$smarty->left_delimiter = '<{';// Set left and right   Prevent and js css  Etc. in conflict 
$smarty->right_delimiter = '}>';
?>


Related articles: