PHP designers who are just starting to get involved in template engines will find it difficult when they hear Smarty. In fact, I am no exception and I dare not touch it. But later when analyzing the program architecture of XOOPS, I began to find that Smarty is actually not difficult. As long as you practice the basic Smarty skills well, it will be quite sufficient in general applications. Of course, the foundation can be laid well, so there is no need to worry about the advanced applications in the future.
The main purpose of this article is not to discuss the use of Smarty in depth, which is already very complete in the official instructions for use. The author only writes down some of his own experiences here, so that friends who want to understand Smarty but cannot get in touch can get some inspiration from it. Just because the content of this article is not very in-depth, friends who know how to use Smarty may find it a little simpler.
This article has been revised for the third time, and I wanted to add more materials. However, due to time, I have not studied many of the advanced techniques of Smarty very thoroughly, so I dare not take them out, but I believe that this article should be able to satisfy most beginners who want to learn Smarty. Of course, if there are any fallacies in this article, you are welcome to inform us, and the author will correct it in the next revision.
Introduction to Smarty
What is a template engine
I don’t know when it started, but some people began to feel unsatisfied with the HTML embedded in Server Script. However, whether it is Microsoft's ASP or open source PHP, it is a web server-side language with embedded Server Script. Therefore, some people thought that if the program application logic (or commercial application logic) can be separated from the web page presentation (Layout) logic, would it be better?
In fact, this problem has existed for a long time. When interactive web pages became popular, both ASP and PHP users were both program developers and visual designers. However, these users are either strong programs or strong artists. If they want to take into account both, many brain cells will be killed...
So the template engine came into being! The purpose of the template engine is to achieve the logical separation function mentioned above. It allows program developers to focus on data control or function implementation; while visual designers can focus on web page layout, making web pages look more professional! Therefore, the template engine is very suitable for the company's website development team, so that everyone can use their expertise!
As for the template engines that I have come into contact with, according to the data presentation method, it is roughly divided into two forms: template engines that need to be processed with programs and template engines that are entirely determined by the template version.
In a template engine that needs to be processed with a program, the program developer must be responsible for the variable presentation logic, that is, he must process the content of the variable before outputting it to the template before he can do the assign work. In other words, program developers still have to write more programs to determine the appearance of variables. The template engine, which is entirely determined by the template version itself, allows variables to be directly assigned to the template, allowing visual designers to decide how the variables should be presented when designing the template. Therefore, it may have another set of its own template program syntax (such as Smarty) to facilitate the presentation of variables. But in this way, visual designers also have to learn how to use the template language.
To operate the template engine, let’s first look at the following running diagram:
General template engines (such as PHPLib) obtain the template to be parsed when creating template objects, then put the variables in, parse the template through parse(), and finally output the web page.
For Smarty users, there is no need to do any parse actions in the program, and these Smarty will automatically help us do them. Moreover, if the template of a compiled web page does not change, Smarty will automatically skip the compiled action and directly execute the compiled web page to save compilation time.
Some concepts of using Smarty
In general template engines, we often see the concept of regions, and the so-called blocks will probably grow like this:
<!-- START : Block name -->
Regional content
<!-- END : Block name -->
Most of these blocks will be controlled by if or for, while in the PHP program. Although the template looks much simpler, as long as the template with a different display method is changed, the PHP program will have to be changed again!
In Smarty, everything is mainly variables, and all presentation logic is controlled by the template. Because Smarty has its own template language, whether the blocks need to be displayed or repeated, they are presented with Smarty's template syntax (if, foreach, section) with variable content. This makes the template feel a bit complicated, but the advantage is that as long as the planning is done properly, there is no need to change a single line of the PHP program.
From the above explanation, we can know that using Smarty requires one principle: clearly separate the application logic of the program from the presentation logic of the web page. That is to say, there should not be too much HTML code in the PHP program. In the program, just decide which variables are fortified into the template and let the template decide on how to present these variables (even if they don’t appear).
The Basics of Smarty
Install Smarty
First, we decide where the program is placed.
There may be a location similar to this in Windows: "d:appservwebdemo ".
There may be a location similar to this in Linux: " /home/jaceju/public_html/ ".
Download the latest Smarty suite at Smarty's official website:.
After unpacking Smarty 2.6.0, you will see many files, including a libs folder. There should be 3 files + 1 + 1 plugin folder + 1 core folder in libs. Then copy libs directly to your program's main folder and then change the name to class. that's all? That's right! This installation method is relatively simple and is suitable for users who do not have their own host.
As for why the Smarty official manual introduces some more complex installation methods? Basically, it is installed in the official way. It can be installed only once on the host and then provided to all designers under the host to directly reference when developing different programs, without repeatedly installing too many Smarty copies. The method provided by the author is suitable for program developers who want to bring the program over to move it, so that they don’t have to worry about whether the host has Smarty installed.
Program folder settings
Taking the author installing Appserv on Windows as an example, the main folder of the program is "d:appservwebdemo". After installing Smarty, we create such a folder under the main folder:
Under Linux, please remember to change the permissions of templates_c to 777. Under Windows, it will only be canceled.
The first applet written in Smarty
Let’s first set the path to Smarty. Please name the following file as and place it in the main folder:
:
<?php
include "class/";
define(@#__SITE_ROOT@#,@#d:/appserv/web/demo@#);// There is no slash in the end
$tpl = new Smarty();
$tpl->template_dir = __SITE_ROOT . "/templates/";
$tpl->compile_dir = __SITE_ROOT . "/templates_c/";
$tpl->config_dir = __SITE_ROOT . "/configs/";
$tpl->cache_dir = __SITE_ROOT . "/cache/";
$tpl->left_delimiter = @#<{@#;
$tpl->right_delimiter = @#}>@#;
?>
The purpose of setting the above method is that if the program is to be ported to another place, just change __SITE_ROOT. (This is the reference for XOOPS)
After the template path of Smarty is set, the program will follow this path to capture the relative position of all templates (in the example, @#d:/appserv/web/demo/templates/@#) . Then we use the Smarty method of display() to display our template.
Next, we place a .htm in the templates folder: (It doesn’t matter what the extension is, but it’s easy for visual designers to develop. The author still focuses on .htm.)
templates/:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>
Now we want to display the template above and replace the web page title ($title) with content ($content). Please name the following archive content and place it in the main folder:
:
<?php
require "";
$tpl->assign("title", "Title for testing");
$tpl->assign("content", "Web page content for testing");
// The above two lines can also be replaced by this line.
// $tpl->assign(array("title" => "Web page title for testing", "content" => "Web page content for testing"));
$tpl->display(@#@#);
?>
Please open the browser and enter http://localhost/demo/ to try it (the URL is determined according to your environment), and you should see the following screen:
Then under templates_c, we will see a strange folder (%%179) and click on it to select a strange folder (%%1798044067), and there is a file in it:
templates_c/%%179/%%1798044067/:
<?php /* Smarty version 2.6.0, created on 2003-12-15 22:19:45 compiled from */ ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><?php echo $this->_tpl_vars[@#title@#]; ?></title>
</head>
<body>
<?php echo $this->_tpl_vars[@#content@#]; ?>
</body>
</html>
That's right, this is the archive compiled by Smarty. It converts the variables we have in the template into PHP syntax for execution. The next time we read the same content, Smarty will directly grab the file to execute.
Finally, let’s sort out the steps for writing the entire Smarty program:
Step 1. Load the Smarty template engine.
Step 2. Create a Smarty object.
Step 3. Set the parameters of the Smarty object.
Step 4. After processing variables in the program, use Smarty’s assign method to place the variables into the template.
Step 5. Use Smarty’s display method to show the web page.
How to arrange your program structure
Above we see that in addition to the folders required by Smarty (class, configs, templates, templates_c), there are two folders: include and modules. In fact, this is built by the author imitating the architecture of XOOPS, because XOOPS is a few station programs that use the Smarty template engine among the programs I have come into contact with. The so-called watermelon snuggles around. Although the author’s program architecture is not as strong as XOOPS, at least it still supports XOOPS when it comes to people.
include This folder is mainly used to place some functions and sql files, so that they can be introduced in , as follows:
:
<?php
include "class/";
define(@#__SITE_ROOT@#,@#d:/appserv/web/demo@#);// There is no slash in the end
// Based on the position of
require_once "includes/";
require_once "includes/";
$tpl = new Smarty();
$tpl->template_dir = __SITE_ROOT . "/templates/";
$tpl->compile_dir = __SITE_ROOT . "/templates_c/";
$tpl->config_dir = __SITE_ROOT . "/configs/";
$tpl->cache_dir = __SITE_ROOT . "/cache/";
$tpl->left_delimiter = @#<{@#;
$tpl->right_delimiter = @#}>@#;
?>
modules This folder is used to place program modules, so that the program will not be thrown everywhere, and the overall architecture is clear at a glance.
We also mentioned above that this is the main core of the entire program, whether it is constant definition, external program loading, shared variable establishment, etc., it all starts here. So the subsequent modules are just included in the file. Therefore, during the program process planning period, you must carefully conceive what should be put in the process; of course, it is best to use include or require instructions to clearly separate each link.
In the 5 steps of the Smarty program mentioned in the previous section, we will help us complete the first 3 steps first, and the subsequent module program only needs to do the next two steps.
Start with a variable
How to use variables
From the example in the previous chapter, we can clearly see that we use the two markers to wrap variables. The preset marking symbols are { and } , but for the relationship between Chinese code and javascript, the author still imitates XOOPS and replaces the marking symbols. The naming method of variables is exactly the same as that of PHP, and there is also a $ font size in front (this is different from general template engines). The marker is a bit like in PHP
<?php and ?>
(In fact, they will indeed be replaced by this), so the following template variable writing methods are feasible:
1. <{$var}>
2.<{ $var }> <!-- There is a space between the variable -->
3. <{$var
}> <!-- The start marker and the end marker are not on the same line ->
In Smarty, variable presets are all-area, which means you just need to specify them once. If specified more than twice, the variable content will be mainly specified. Even if we load external sub-templates in the main template, the same variables in the sub-template will be replaced, so we don't have to do another parse action for the sub-template.
In the PHP program, we use Smarty’s assign to place variables into the template. Assign’s official manual has written a lot, and the usage is as shown in the example in the previous section. However, when repeating the block, we must do some tricks to transfer the variables to the template, which will be mentioned in the next chapter.
Modify your variables
As we mentioned above, the appearance of the Smarty variable is determined by the template, so Smarty provides many functions that modify variables. The methods used are as follows:
<{Variable|Modify Function}> <!-- When the Modify Function has no parameters -->
<{Variable|Modify Function: "Parameters (unnecessary, depending on the function)"}> <!-- When the Modify Function has parameters -->
Examples are as follows:
<{$var|nl2br}> <!-- Fresh newline characters in the variable with <br />
<{$var|string_format:"%02d"}> <!-- Format the variable -->
OK, then why do you have to let the template decide the appearance of the variables? Let’s take a look at the HTML below, which is part of the screen of checkout in a shopping cart.
<input name="total" type="hidden" value="21000" />
Total amount: RMB 21,000
The templates of the general template engine may be written like this:
<input name="total" type="hidden" value="{total}" />
Total amount: {format_total} yuan
Their PHP program should be written like this:
<?php
$total = 21000;
$tpl->assign("total", $total);
$tpl->assign("format_total", number_format($total));
?>
And the Smarty template can be written like this: (number_format, please download it from the Smarty official website)
<input name="total" type="hidden" value="<{$total}>" />
Total amount: <{$total|number_format:""}> RMB
Smarty’s PHP program just write this way:
<?php
$total = 21000;
$tpl->assign("total", $total);
?>
So in Smarty, we just need to specify the variable once and leave the rest to the template to decide for yourself. Did you understand this way? This is the benefit of letting the template decide the variables to show their own style!
Control the content of the template
Repeated blocks
In the Smarty sample, there are two ways to repeat a block: foreach and section. In the program, we need to assign an array, which can contain array arrays. Like the following example:
First, let’s take a look at how the PHP program is written:
:
<?php
require "";
$array1 = array(1 => "Apple", 2 => "Pineapple", 3 => "Banana", 4 => "Guava");
$tpl->assign("array1", $array1);
$array2 = array(
array("index1" => "data1-1", "index2" => "data1-2", "index3" => "data1-3"),
array("index1" => "data2-1", "index2" => "data2-2", "index3" => "data2-3"),
array("index1" => "data3-1", "index2" => "data3-2", "index3" => "data3-3"),
array("index1" => "data4-1", "index2" => "data4-2", "index3" => "data4-3"),
array("index1" => "data5-1", "index2" => "data5-2", "index3" => "data5-3"));
$tpl->assign("array2", $array2);
$tpl->display("");
?>
The template is written as follows:
templates/:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>Test repeated blocks</title>
</head>
<body>
<pre>
Use foreach to present array1
<{foreach item=item1 from=$array1}>
<{$item1}>
<{/foreach}>
Use section to present array1
<{section name=sec1 loop=$array1}>
<{$array1[sec1]}>
<{/section}>
Use foreach to present array2
<{foreach item=index2 from=$array2}>
<{foreach key=key2 item=item2 from=$index2}>
<{$key2}>: <{$item2}>
<{/foreach}>
<{/foreach}>
Use section to present array1
<{section name=sec2 loop=$array2}>
index1: <{$array2[sec2].index1}>
index2: <{$array2[sec2].index2}>
index3: <{$array2[sec2].index3}>
<{/section}>
</pre>
</body>
</html>
After executing the above example, we found that the results of both executions are the same, whether it is foreach or section. So what is the difference between the two?
The first difference is obvious, that is, foreach should present the two-layer array variables we assign in a nest-like manner, while section can present the entire array with "main array [loop name]. subarray index". From this we can see that Smarty's foreach in the template is the same as PHP's foreach; and section is a narrative developed by Smarty to deal with array variables as listed above. Of course, the function of section is not only that. In addition to the nest-like data presentation mentioned in the next section, the official manual also provides several application examples of sections.
However, it should be noted that the array index thrown to section must be a positive integer starting from 0, i.e. 0, 1, 2, 3, .... If your array index is not a positive integer starting from 0, you have to use foreach to present your data instead. You can refer to this discussion in the official discussion area, which discusses the usage of section and foreach.
Presentation of nest-like data
The most troublesome thing in the template engine is probably the presentation of nest-like data. Many famous template engines will specifically emphasize this point, but this is a pediatric for Smarty.
The most common nest-like information is considered the topic area of the discussion program. Assume the results to be presented are as follows:
Announcement area
Station Service Announcement
Literary Zone
Good book introduction
Appreciate strange texts together
Computer Zone
Hardware peripherals
Software discussion
In the program, let’s take static data as an example:
:
<?php
require "";
$forum = array(
array("category_id" => 1, "category_name" => "Announcement Area",
"topic" => array(
array("topic_id" => 1, "topic_name" => "Site Affairs Announcement")
)
),
array("category_id" => 2, "category_name" => "Literature Zone",
"topic" => array(
array("topic_id" => 2, "topic_name" => "Good book introduction"),
array("topic_id" => 3, "topic_name" => "Single texts to appreciate")
)
),
array("category_id" => 3, "category_name" => "Computer Zone",
"topic" => array(
array("topic_id" => 4, "topic_name" => "Hardware peripheral"),
array("topic_id" => 5, "topic_name" => "Software Discussion")
)
)
);
$tpl->assign("forum", $forum);
$tpl->display("");
?>
The template is written as follows:
templates/:
<html>
<head>
<title>Nest-like cycle test</title>
</head>
<body>
<table width="200" border="0" align="center" cellpadding="3" cellspacing="0">
<{section name=sec1 loop=$forum}>
<tr>
<td colspan="2"><{$forum[sec1].category_name}></td>
</tr>
<{section name=sec2 loop=$forum[sec1].topic}>
<tr>
<td width="25"> </td>
<td width="164"><{$forum[sec1].topic[sec2].topic_name}></td>
</tr>
<{/section}>
<{/section}>
</table>
</body>
</html>
The execution result is like the example I give.
Therefore, in the program, we just need to find a way to stuff the repetitive values into the array layer by layer, and then use <{The first layer array [loop 1], the second layer array [loop 2], the third layer array [loop 3].....Array index}> to display the values in each nested loop. As for what method to use? We will mention it when using the database in the next section.
Convert data in the database
The above mentioned how to display nest-like loops, but in fact, our data may be captured from the database when applied, so we have to find a way to turn the data of the database into the above multiple arrays. Here, the author uses a DB category to capture information in the database, and you can use the method you like.
We only modify the PHP program, and the template is still the one above (this is the benefit of the template engine~), and the object assumption of the $db object has been established in it, and the data captured is the example above.
:
<?php
require "";
// Create the first layer array first
$category = array();
$db->setSQL($SQL1, @#CATEGORY@#);
if (!$db->query(@#CATEGORY@#)) die($db->error());
//Catch the first layer of loop information
while ($item_category = $db->fetchAssoc(@#CATEGORY@#))
{
// Create a second layer array
$topic = array();
$db->setSQL(sprintf($SQL2, $item_category[@#category_id@#]), @#TOPIC@#);
if (!$db->query(@#TOPIC@#)) die($db->error());
//Crawl the information of the second layer of loop
while ($item_topic = $db->fetchAssoc(@#TOPIC@#))
{
// Push the crawled data into the second layer array
array_push($topic, $item_topic);
}
//Specify the second layer array as a member of the data captured by the first layer array
$item_category[@#topic@#] = $topic;
// Push the first layer of data into the first layer of array
array_push($category, $item_category);
}
$tpl->assign("forum", $category);
$tpl->display("");
?>
After grabbing a piece of data in the database, we get an array containing the piece of data. Through the while narrative and array_push function, we stuff the data in the database into the array one by one. If you only use a single-layer loop, just remove the second loop (the red part).
Decide whether the content is displayed
To decide whether to display content, we can use the if syntax to make a choice. For example, if the user is already logged in, our template can be written like this:
<{if $is_login == true}>
Display user action menu
<{else}>
Display the form to enter the account number and password
<{/if}>
It should be noted that at least one space character must be left on both sides of the "==" sign, otherwise Smarty will not be able to parse.
if General applications of grammar can be referred to the official instructions, so I will not introduce it in detail here. However, the author discovered an interesting application: I often see a table like this in the program: (numbers represent the order of data sets)
1 2
3 4
5 6
7 8
This author calls it a "horizontal repeat form". Its characteristics are different from traditional vertical repetitions. The repetition tables we saw in the previous sections are all from top to bottom, with only one piece of information in a column. The horizontal repeat table can generate n pieces of information horizontally in one column and then replace the next column until the entire cycle ends. To achieve such a function, the easiest way is to match section and if.
Let's take a look at the following example:
:
<?php
require "";
$my_array = array(
array("value" => "0"),
array("value" => "1"),
array("value" => "2"),
array("value" => "3"),
array("value" => "4"),
array("value" => "5"),
array("value" => "6"),
array("value" => "7"),
array("value" => "8"),
array("value" => "9"));
$tpl->assign("my_array", $my_array);
$tpl->display(@#@#);
?>
The template is written as follows:
templates/:
<html>
<head>
<title>Horizontal repeat table test</title>
</head>
<body>
<table width="500" border="1" cellspacing="0" cellpadding="3">
<tr>
<{section name=sec1 loop=$my_array}>
<td><{$my_array[sec1].value}></td>
<{if $. is div by 2}>
</tr>
<tr>
<{/if}>
<{/section}>
</tr>
</table>
</body>
</html>
The key point is $. This Smarty variable. In the section loop, this variable will get the index value starting from 1, so when rownum can be divided by 2, it will output </tr><tr> to change the table (note! Yes </tr> in front <tr> in back). Therefore, the number 2 is the number of data we want to present in a column. You can change other different presentation methods from this.
Load external content
We can load PHP program code or another sub-template in the template, using the two Smarty template syntaxes: include_php and include; include_php is rarely used by the author, so you can check the official manual for the use method, which will not be described here.
When using include, we can preload sub-templates, or dynamically load sub-templates. Pre-loading is usually used in common file headers and copyright declarations; while dynamic loading can be used in unified framework pages, and further reaches the Skin like Winamp. Of course, we can also mix these two, depending on the situation.
Let's take a look at the following example:
:
<?php
require "";
$tpl->assign("title", "Include test");
$tpl->assign("content", "This is a variable in template 2");
$tpl->assign("dyn_page", "test5_3.htm");
$tpl->display(@#test5_1.htm@#);
?>
The writing method of Template 1 is as follows:
templates/test5_1.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><{$title}></title>
</head>
<body>
<{include file="test5_2.htm"}><br />
<{include file=$dyn_page}>
<{include file="test5_4.htm" custom_var="Content of Custom Variables"}>
</body>
</html>
The writing of Template 2 is as follows:
templates/test5_2.htm:
<{$content}>
The writing of Template 3 is as follows:
templates/test5_3.htm:
This is the content of Template 3
The writing of Template 4 is as follows:
templates/test5_4.htm:
<{$custom_var}>
Here are a few key points: 1. The position of the template is based on the previously defined template_dir; 2. The variables in all sub-templates that include come in will also be interpreted. ;3. In include, you can use "variable name = variable content" to specify the variables contained in the template included, just like the above template 4.
The main purpose of this article is not to discuss the use of Smarty in depth, which is already very complete in the official instructions for use. The author only writes down some of his own experiences here, so that friends who want to understand Smarty but cannot get in touch can get some inspiration from it. Just because the content of this article is not very in-depth, friends who know how to use Smarty may find it a little simpler.
This article has been revised for the third time, and I wanted to add more materials. However, due to time, I have not studied many of the advanced techniques of Smarty very thoroughly, so I dare not take them out, but I believe that this article should be able to satisfy most beginners who want to learn Smarty. Of course, if there are any fallacies in this article, you are welcome to inform us, and the author will correct it in the next revision.
Introduction to Smarty
What is a template engine
I don’t know when it started, but some people began to feel unsatisfied with the HTML embedded in Server Script. However, whether it is Microsoft's ASP or open source PHP, it is a web server-side language with embedded Server Script. Therefore, some people thought that if the program application logic (or commercial application logic) can be separated from the web page presentation (Layout) logic, would it be better?
In fact, this problem has existed for a long time. When interactive web pages became popular, both ASP and PHP users were both program developers and visual designers. However, these users are either strong programs or strong artists. If they want to take into account both, many brain cells will be killed...
So the template engine came into being! The purpose of the template engine is to achieve the logical separation function mentioned above. It allows program developers to focus on data control or function implementation; while visual designers can focus on web page layout, making web pages look more professional! Therefore, the template engine is very suitable for the company's website development team, so that everyone can use their expertise!
As for the template engines that I have come into contact with, according to the data presentation method, it is roughly divided into two forms: template engines that need to be processed with programs and template engines that are entirely determined by the template version.
In a template engine that needs to be processed with a program, the program developer must be responsible for the variable presentation logic, that is, he must process the content of the variable before outputting it to the template before he can do the assign work. In other words, program developers still have to write more programs to determine the appearance of variables. The template engine, which is entirely determined by the template version itself, allows variables to be directly assigned to the template, allowing visual designers to decide how the variables should be presented when designing the template. Therefore, it may have another set of its own template program syntax (such as Smarty) to facilitate the presentation of variables. But in this way, visual designers also have to learn how to use the template language.
To operate the template engine, let’s first look at the following running diagram:
General template engines (such as PHPLib) obtain the template to be parsed when creating template objects, then put the variables in, parse the template through parse(), and finally output the web page.
For Smarty users, there is no need to do any parse actions in the program, and these Smarty will automatically help us do them. Moreover, if the template of a compiled web page does not change, Smarty will automatically skip the compiled action and directly execute the compiled web page to save compilation time.
Some concepts of using Smarty
In general template engines, we often see the concept of regions, and the so-called blocks will probably grow like this:
<!-- START : Block name -->
Regional content
<!-- END : Block name -->
Most of these blocks will be controlled by if or for, while in the PHP program. Although the template looks much simpler, as long as the template with a different display method is changed, the PHP program will have to be changed again!
In Smarty, everything is mainly variables, and all presentation logic is controlled by the template. Because Smarty has its own template language, whether the blocks need to be displayed or repeated, they are presented with Smarty's template syntax (if, foreach, section) with variable content. This makes the template feel a bit complicated, but the advantage is that as long as the planning is done properly, there is no need to change a single line of the PHP program.
From the above explanation, we can know that using Smarty requires one principle: clearly separate the application logic of the program from the presentation logic of the web page. That is to say, there should not be too much HTML code in the PHP program. In the program, just decide which variables are fortified into the template and let the template decide on how to present these variables (even if they don’t appear).
The Basics of Smarty
Install Smarty
First, we decide where the program is placed.
There may be a location similar to this in Windows: "d:appservwebdemo ".
There may be a location similar to this in Linux: " /home/jaceju/public_html/ ".
Download the latest Smarty suite at Smarty's official website:.
After unpacking Smarty 2.6.0, you will see many files, including a libs folder. There should be 3 files + 1 + 1 plugin folder + 1 core folder in libs. Then copy libs directly to your program's main folder and then change the name to class. that's all? That's right! This installation method is relatively simple and is suitable for users who do not have their own host.
As for why the Smarty official manual introduces some more complex installation methods? Basically, it is installed in the official way. It can be installed only once on the host and then provided to all designers under the host to directly reference when developing different programs, without repeatedly installing too many Smarty copies. The method provided by the author is suitable for program developers who want to bring the program over to move it, so that they don’t have to worry about whether the host has Smarty installed.
Program folder settings
Taking the author installing Appserv on Windows as an example, the main folder of the program is "d:appservwebdemo". After installing Smarty, we create such a folder under the main folder:
Under Linux, please remember to change the permissions of templates_c to 777. Under Windows, it will only be canceled.
The first applet written in Smarty
Let’s first set the path to Smarty. Please name the following file as and place it in the main folder:
:
<?php
include "class/";
define(@#__SITE_ROOT@#,@#d:/appserv/web/demo@#);// There is no slash in the end
$tpl = new Smarty();
$tpl->template_dir = __SITE_ROOT . "/templates/";
$tpl->compile_dir = __SITE_ROOT . "/templates_c/";
$tpl->config_dir = __SITE_ROOT . "/configs/";
$tpl->cache_dir = __SITE_ROOT . "/cache/";
$tpl->left_delimiter = @#<{@#;
$tpl->right_delimiter = @#}>@#;
?>
The purpose of setting the above method is that if the program is to be ported to another place, just change __SITE_ROOT. (This is the reference for XOOPS)
After the template path of Smarty is set, the program will follow this path to capture the relative position of all templates (in the example, @#d:/appserv/web/demo/templates/@#) . Then we use the Smarty method of display() to display our template.
Next, we place a .htm in the templates folder: (It doesn’t matter what the extension is, but it’s easy for visual designers to develop. The author still focuses on .htm.)
templates/:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>
Now we want to display the template above and replace the web page title ($title) with content ($content). Please name the following archive content and place it in the main folder:
:
<?php
require "";
$tpl->assign("title", "Title for testing");
$tpl->assign("content", "Web page content for testing");
// The above two lines can also be replaced by this line.
// $tpl->assign(array("title" => "Web page title for testing", "content" => "Web page content for testing"));
$tpl->display(@#@#);
?>
Please open the browser and enter http://localhost/demo/ to try it (the URL is determined according to your environment), and you should see the following screen:
Then under templates_c, we will see a strange folder (%%179) and click on it to select a strange folder (%%1798044067), and there is a file in it:
templates_c/%%179/%%1798044067/:
<?php /* Smarty version 2.6.0, created on 2003-12-15 22:19:45 compiled from */ ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><?php echo $this->_tpl_vars[@#title@#]; ?></title>
</head>
<body>
<?php echo $this->_tpl_vars[@#content@#]; ?>
</body>
</html>
That's right, this is the archive compiled by Smarty. It converts the variables we have in the template into PHP syntax for execution. The next time we read the same content, Smarty will directly grab the file to execute.
Finally, let’s sort out the steps for writing the entire Smarty program:
Step 1. Load the Smarty template engine.
Step 2. Create a Smarty object.
Step 3. Set the parameters of the Smarty object.
Step 4. After processing variables in the program, use Smarty’s assign method to place the variables into the template.
Step 5. Use Smarty’s display method to show the web page.
How to arrange your program structure
Above we see that in addition to the folders required by Smarty (class, configs, templates, templates_c), there are two folders: include and modules. In fact, this is built by the author imitating the architecture of XOOPS, because XOOPS is a few station programs that use the Smarty template engine among the programs I have come into contact with. The so-called watermelon snuggles around. Although the author’s program architecture is not as strong as XOOPS, at least it still supports XOOPS when it comes to people.
include This folder is mainly used to place some functions and sql files, so that they can be introduced in , as follows:
:
<?php
include "class/";
define(@#__SITE_ROOT@#,@#d:/appserv/web/demo@#);// There is no slash in the end
// Based on the position of
require_once "includes/";
require_once "includes/";
$tpl = new Smarty();
$tpl->template_dir = __SITE_ROOT . "/templates/";
$tpl->compile_dir = __SITE_ROOT . "/templates_c/";
$tpl->config_dir = __SITE_ROOT . "/configs/";
$tpl->cache_dir = __SITE_ROOT . "/cache/";
$tpl->left_delimiter = @#<{@#;
$tpl->right_delimiter = @#}>@#;
?>
modules This folder is used to place program modules, so that the program will not be thrown everywhere, and the overall architecture is clear at a glance.
We also mentioned above that this is the main core of the entire program, whether it is constant definition, external program loading, shared variable establishment, etc., it all starts here. So the subsequent modules are just included in the file. Therefore, during the program process planning period, you must carefully conceive what should be put in the process; of course, it is best to use include or require instructions to clearly separate each link.
In the 5 steps of the Smarty program mentioned in the previous section, we will help us complete the first 3 steps first, and the subsequent module program only needs to do the next two steps.
Start with a variable
How to use variables
From the example in the previous chapter, we can clearly see that we use the two markers to wrap variables. The preset marking symbols are { and } , but for the relationship between Chinese code and javascript, the author still imitates XOOPS and replaces the marking symbols. The naming method of variables is exactly the same as that of PHP, and there is also a $ font size in front (this is different from general template engines). The marker is a bit like in PHP
<?php and ?>
(In fact, they will indeed be replaced by this), so the following template variable writing methods are feasible:
1. <{$var}>
2.<{ $var }> <!-- There is a space between the variable -->
3. <{$var
}> <!-- The start marker and the end marker are not on the same line ->
In Smarty, variable presets are all-area, which means you just need to specify them once. If specified more than twice, the variable content will be mainly specified. Even if we load external sub-templates in the main template, the same variables in the sub-template will be replaced, so we don't have to do another parse action for the sub-template.
In the PHP program, we use Smarty’s assign to place variables into the template. Assign’s official manual has written a lot, and the usage is as shown in the example in the previous section. However, when repeating the block, we must do some tricks to transfer the variables to the template, which will be mentioned in the next chapter.
Modify your variables
As we mentioned above, the appearance of the Smarty variable is determined by the template, so Smarty provides many functions that modify variables. The methods used are as follows:
<{Variable|Modify Function}> <!-- When the Modify Function has no parameters -->
<{Variable|Modify Function: "Parameters (unnecessary, depending on the function)"}> <!-- When the Modify Function has parameters -->
Examples are as follows:
<{$var|nl2br}> <!-- Fresh newline characters in the variable with <br />
<{$var|string_format:"%02d"}> <!-- Format the variable -->
OK, then why do you have to let the template decide the appearance of the variables? Let’s take a look at the HTML below, which is part of the screen of checkout in a shopping cart.
<input name="total" type="hidden" value="21000" />
Total amount: RMB 21,000
The templates of the general template engine may be written like this:
<input name="total" type="hidden" value="{total}" />
Total amount: {format_total} yuan
Their PHP program should be written like this:
<?php
$total = 21000;
$tpl->assign("total", $total);
$tpl->assign("format_total", number_format($total));
?>
And the Smarty template can be written like this: (number_format, please download it from the Smarty official website)
<input name="total" type="hidden" value="<{$total}>" />
Total amount: <{$total|number_format:""}> RMB
Smarty’s PHP program just write this way:
<?php
$total = 21000;
$tpl->assign("total", $total);
?>
So in Smarty, we just need to specify the variable once and leave the rest to the template to decide for yourself. Did you understand this way? This is the benefit of letting the template decide the variables to show their own style!
Control the content of the template
Repeated blocks
In the Smarty sample, there are two ways to repeat a block: foreach and section. In the program, we need to assign an array, which can contain array arrays. Like the following example:
First, let’s take a look at how the PHP program is written:
:
<?php
require "";
$array1 = array(1 => "Apple", 2 => "Pineapple", 3 => "Banana", 4 => "Guava");
$tpl->assign("array1", $array1);
$array2 = array(
array("index1" => "data1-1", "index2" => "data1-2", "index3" => "data1-3"),
array("index1" => "data2-1", "index2" => "data2-2", "index3" => "data2-3"),
array("index1" => "data3-1", "index2" => "data3-2", "index3" => "data3-3"),
array("index1" => "data4-1", "index2" => "data4-2", "index3" => "data4-3"),
array("index1" => "data5-1", "index2" => "data5-2", "index3" => "data5-3"));
$tpl->assign("array2", $array2);
$tpl->display("");
?>
The template is written as follows:
templates/:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>Test repeated blocks</title>
</head>
<body>
<pre>
Use foreach to present array1
<{foreach item=item1 from=$array1}>
<{$item1}>
<{/foreach}>
Use section to present array1
<{section name=sec1 loop=$array1}>
<{$array1[sec1]}>
<{/section}>
Use foreach to present array2
<{foreach item=index2 from=$array2}>
<{foreach key=key2 item=item2 from=$index2}>
<{$key2}>: <{$item2}>
<{/foreach}>
<{/foreach}>
Use section to present array1
<{section name=sec2 loop=$array2}>
index1: <{$array2[sec2].index1}>
index2: <{$array2[sec2].index2}>
index3: <{$array2[sec2].index3}>
<{/section}>
</pre>
</body>
</html>
After executing the above example, we found that the results of both executions are the same, whether it is foreach or section. So what is the difference between the two?
The first difference is obvious, that is, foreach should present the two-layer array variables we assign in a nest-like manner, while section can present the entire array with "main array [loop name]. subarray index". From this we can see that Smarty's foreach in the template is the same as PHP's foreach; and section is a narrative developed by Smarty to deal with array variables as listed above. Of course, the function of section is not only that. In addition to the nest-like data presentation mentioned in the next section, the official manual also provides several application examples of sections.
However, it should be noted that the array index thrown to section must be a positive integer starting from 0, i.e. 0, 1, 2, 3, .... If your array index is not a positive integer starting from 0, you have to use foreach to present your data instead. You can refer to this discussion in the official discussion area, which discusses the usage of section and foreach.
Presentation of nest-like data
The most troublesome thing in the template engine is probably the presentation of nest-like data. Many famous template engines will specifically emphasize this point, but this is a pediatric for Smarty.
The most common nest-like information is considered the topic area of the discussion program. Assume the results to be presented are as follows:
Announcement area
Station Service Announcement
Literary Zone
Good book introduction
Appreciate strange texts together
Computer Zone
Hardware peripherals
Software discussion
In the program, let’s take static data as an example:
:
<?php
require "";
$forum = array(
array("category_id" => 1, "category_name" => "Announcement Area",
"topic" => array(
array("topic_id" => 1, "topic_name" => "Site Affairs Announcement")
)
),
array("category_id" => 2, "category_name" => "Literature Zone",
"topic" => array(
array("topic_id" => 2, "topic_name" => "Good book introduction"),
array("topic_id" => 3, "topic_name" => "Single texts to appreciate")
)
),
array("category_id" => 3, "category_name" => "Computer Zone",
"topic" => array(
array("topic_id" => 4, "topic_name" => "Hardware peripheral"),
array("topic_id" => 5, "topic_name" => "Software Discussion")
)
)
);
$tpl->assign("forum", $forum);
$tpl->display("");
?>
The template is written as follows:
templates/:
<html>
<head>
<title>Nest-like cycle test</title>
</head>
<body>
<table width="200" border="0" align="center" cellpadding="3" cellspacing="0">
<{section name=sec1 loop=$forum}>
<tr>
<td colspan="2"><{$forum[sec1].category_name}></td>
</tr>
<{section name=sec2 loop=$forum[sec1].topic}>
<tr>
<td width="25"> </td>
<td width="164"><{$forum[sec1].topic[sec2].topic_name}></td>
</tr>
<{/section}>
<{/section}>
</table>
</body>
</html>
The execution result is like the example I give.
Therefore, in the program, we just need to find a way to stuff the repetitive values into the array layer by layer, and then use <{The first layer array [loop 1], the second layer array [loop 2], the third layer array [loop 3].....Array index}> to display the values in each nested loop. As for what method to use? We will mention it when using the database in the next section.
Convert data in the database
The above mentioned how to display nest-like loops, but in fact, our data may be captured from the database when applied, so we have to find a way to turn the data of the database into the above multiple arrays. Here, the author uses a DB category to capture information in the database, and you can use the method you like.
We only modify the PHP program, and the template is still the one above (this is the benefit of the template engine~), and the object assumption of the $db object has been established in it, and the data captured is the example above.
:
<?php
require "";
// Create the first layer array first
$category = array();
$db->setSQL($SQL1, @#CATEGORY@#);
if (!$db->query(@#CATEGORY@#)) die($db->error());
//Catch the first layer of loop information
while ($item_category = $db->fetchAssoc(@#CATEGORY@#))
{
// Create a second layer array
$topic = array();
$db->setSQL(sprintf($SQL2, $item_category[@#category_id@#]), @#TOPIC@#);
if (!$db->query(@#TOPIC@#)) die($db->error());
//Crawl the information of the second layer of loop
while ($item_topic = $db->fetchAssoc(@#TOPIC@#))
{
// Push the crawled data into the second layer array
array_push($topic, $item_topic);
}
//Specify the second layer array as a member of the data captured by the first layer array
$item_category[@#topic@#] = $topic;
// Push the first layer of data into the first layer of array
array_push($category, $item_category);
}
$tpl->assign("forum", $category);
$tpl->display("");
?>
After grabbing a piece of data in the database, we get an array containing the piece of data. Through the while narrative and array_push function, we stuff the data in the database into the array one by one. If you only use a single-layer loop, just remove the second loop (the red part).
Decide whether the content is displayed
To decide whether to display content, we can use the if syntax to make a choice. For example, if the user is already logged in, our template can be written like this:
<{if $is_login == true}>
Display user action menu
<{else}>
Display the form to enter the account number and password
<{/if}>
It should be noted that at least one space character must be left on both sides of the "==" sign, otherwise Smarty will not be able to parse.
if General applications of grammar can be referred to the official instructions, so I will not introduce it in detail here. However, the author discovered an interesting application: I often see a table like this in the program: (numbers represent the order of data sets)
1 2
3 4
5 6
7 8
This author calls it a "horizontal repeat form". Its characteristics are different from traditional vertical repetitions. The repetition tables we saw in the previous sections are all from top to bottom, with only one piece of information in a column. The horizontal repeat table can generate n pieces of information horizontally in one column and then replace the next column until the entire cycle ends. To achieve such a function, the easiest way is to match section and if.
Let's take a look at the following example:
:
<?php
require "";
$my_array = array(
array("value" => "0"),
array("value" => "1"),
array("value" => "2"),
array("value" => "3"),
array("value" => "4"),
array("value" => "5"),
array("value" => "6"),
array("value" => "7"),
array("value" => "8"),
array("value" => "9"));
$tpl->assign("my_array", $my_array);
$tpl->display(@#@#);
?>
The template is written as follows:
templates/:
<html>
<head>
<title>Horizontal repeat table test</title>
</head>
<body>
<table width="500" border="1" cellspacing="0" cellpadding="3">
<tr>
<{section name=sec1 loop=$my_array}>
<td><{$my_array[sec1].value}></td>
<{if $. is div by 2}>
</tr>
<tr>
<{/if}>
<{/section}>
</tr>
</table>
</body>
</html>
The key point is $. This Smarty variable. In the section loop, this variable will get the index value starting from 1, so when rownum can be divided by 2, it will output </tr><tr> to change the table (note! Yes </tr> in front <tr> in back). Therefore, the number 2 is the number of data we want to present in a column. You can change other different presentation methods from this.
Load external content
We can load PHP program code or another sub-template in the template, using the two Smarty template syntaxes: include_php and include; include_php is rarely used by the author, so you can check the official manual for the use method, which will not be described here.
When using include, we can preload sub-templates, or dynamically load sub-templates. Pre-loading is usually used in common file headers and copyright declarations; while dynamic loading can be used in unified framework pages, and further reaches the Skin like Winamp. Of course, we can also mix these two, depending on the situation.
Let's take a look at the following example:
:
<?php
require "";
$tpl->assign("title", "Include test");
$tpl->assign("content", "This is a variable in template 2");
$tpl->assign("dyn_page", "test5_3.htm");
$tpl->display(@#test5_1.htm@#);
?>
The writing method of Template 1 is as follows:
templates/test5_1.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><{$title}></title>
</head>
<body>
<{include file="test5_2.htm"}><br />
<{include file=$dyn_page}>
<{include file="test5_4.htm" custom_var="Content of Custom Variables"}>
</body>
</html>
The writing of Template 2 is as follows:
templates/test5_2.htm:
<{$content}>
The writing of Template 3 is as follows:
templates/test5_3.htm:
This is the content of Template 3
The writing of Template 4 is as follows:
templates/test5_4.htm:
<{$custom_var}>
Here are a few key points: 1. The position of the template is based on the previously defined template_dir; 2. The variables in all sub-templates that include come in will also be interpreted. ;3. In include, you can use "variable name = variable content" to specify the variables contained in the template included, just like the above template 4.