Home > Backend Development > PHP Tutorial > smart flash recovery Getting started with Smarty for beginners learning PHP

smart flash recovery Getting started with Smarty for beginners learning PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-29 08:36:07
Original
1104 people have browsed it

PHP designers who have just started to come into contact with template engines will find it difficult when they hear Smarty. In fact, the author is no exception and dare not touch it. But later when I analyzed the program architecture of XOOPS, I began to find that Smarty is actually not difficult. As long as you master the basic skills of Smarty, it is quite sufficient for general applications. Of course, if you can lay the foundation well, you don’t have to worry about the advanced applications later.
The main purpose of this article is not to delve into the use of Smarty, which has been fully written in the official instructions for use. The author only writes down some of his own experience in using it, so that friends who want to understand Smarty but cannot get in 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 bit simple.
This article has been revised for the third time now. I wanted to add more information; however, due to time constraints, the author has not thoroughly studied many of Smarty’s advanced skills, so I dare not show them to you, but I believe this This article should be able to satisfy most beginners who want to learn Smarty. Of course, you are welcome to let us know if there are any fallacies in this article, and the author will correct them in the next revision.
Introduction to Smarty
What is a template engine?
I don’t know since when, some people started to feel dissatisfied with embedding Server Script in HTML. However, whether it is Microsoft's ASP or open source PHP, they are all web server-side languages ​​with embedded Server Script. Therefore, some people think that it would be better if the program application logic (or business application logic) and the web page presentation (Layout) logic can be separated?
In fact, this problem has existed for a long time. When interactive web pages became popular, users of both ASP and PHP were both program developers and visual designers. But usually these users are either good at programming or good at art. If they want to take care of both at the same time, they will lose a lot of brain cells...
So the template engine came into being! The purpose of the template engine is to achieve the function of logical separation mentioned above. It allows program developers to focus on data control or function realization; while visual designers can focus on web page layout, making the web page look more professional! Therefore, the template engine is suitable for use by the company's website development team, allowing everyone to use their expertise!
As for the template engines that the author has come into contact with, they can be roughly divided into two types according to the data presentation method: template engines that need to be processed by programs and template engines that are completely determined by the template itself.
In a template engine that needs to be processed by a program, the program developer must be responsible for the presentation logic of the variables, which means that he must process the contents of the variables before outputting them to the template before he can do the assignment work. In other words, program developers still have to write more programs to determine the appearance of variables. The template engine, which is completely determined by the template itself, allows variables to be directly assigned to the template, allowing the visual designer to decide how the variables are 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 control variables. But in this way, visual designers also have to learn how to use template language.
The operating principle of the template engine. First, let's take a look at the following operation diagram:
General template engines (such as PHPLib) obtain the template to be parsed when creating a template object, and then insert the variables and use parse( ) This method is used to parse the template and finally output the web page.
For Smarty users, there is no need to do any parse actions in the program, Smarty will automatically do it for us. Moreover, if the template of a compiled web page has not changed, Smarty will automatically skip the compilation action and directly execute the compiled web page to save compilation time.
Using some concepts of Smarty
In general template engines, we often see the concept of regions. The so-called blocks will probably look like this:

Region content
< !-- END : Block name -->
Most of these blocks will use if or for, while to control their display status in PHP programs. Although the template looks much simpler, as soon as the display is changed, With different templates, the PHP program must be changed again!
In Smarty, everything is based on variables, and all presentation logic is controlled by the template. Because Smarty has its own template language, whether a block needs to be displayed or repeated, it is presented using Smarty's template syntax (if, foreach, section) and variable content. In this way, it feels like the template has become a bit complicated, but the advantage is that as long as you plan it properly, you don't have to change a single line of the PHP program.
From the above description, we can know that when using Smarty, we need to master one principle: clearly separate the program application logic and the web page rendering logic. That is to say, there should not be too much HTML code in the PHP program. In the program, you only need to decide which variables should be inserted into the template, and let the template decide how to present these variables (or even not appear at all).
Basics of Smarty
Installing Smarty
First, we first decide where to place the program.
Under Windows, there may be a location similar to this: "d:appservwebdemo".
Under Linux, it may be a location similar to this: "/home/jaceju/public_html/".
Go to Smarty’s official website to download the latest Smarty package: http://smarty.php.net.
After unlocking Smarty 2.6.0, you will see many files, including the libs folder. There should be 3 class.php files + 1 debug.tpl + 1 plugin folder + 1 core folder in libs. Then directly copy libs to your program's main folder, and then rename it to class. that's all? That’s right! This installation method is relatively simple and suitable for users who generally do not have their own host.
As for why the Smarty official manual introduces some more complicated installation methods? Basically, it is installed according to the official method. It can be installed only once on the host, and then provided to all designers under the host for direct reference when developing different programs, without repeatedly installing too many copies of Smarty. The method provided by the author is suitable for program developers who want to move programs here and there, so that they don't have to worry about whether Smarty is installed on the host.
Program folder settings
Take the author's installation of Appserv on Windows as an example. The main folder of the program is "d:appservwebdemo". After installing Smarty, we create a folder like this under the main folder:
Under Linux, please remember to change the permissions of templates_c to 777. Under Windows, cancel it as read-only.
The first small program written with Smarty
We first set the path to Smarty. Please name the following file main.php and place it in the main folder:
main.php:
include "class/Smarty.class.php";
define(@#__SITE_ROOT@#, @#d:/appserv/web/demo@#); // No slash at 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 = @#}>@#;
?>
Photo The purpose of the above setting is that if the program needs to be transplanted to other places, just change __SITE_ROOT. (Here is a reference to XOOPS)
After Smarty's template path is set, the program will follow this path to grab the relative positions of all templates (in the example, it is @#d:/appserv/web/demo/templates/@#). Then we use the display() Smarty method to display our template.
Next, we place a test.htm under the templates folder: (It doesn’t matter what the extension is, but it is convenient for visual designers to develop, so I mainly use .htm.)
templates/test.htm:
< html>

$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 scattered everywhere, and the overall structure will be clear at a glance
We also mentioned main. php, this is the main core of the entire program. Whether it is constant definition, external program loading, shared variable creation, etc., it all starts here. Therefore, subsequent modules only need to include this file in the program flow. During the planning period, you must carefully think about what should be placed in main.php; of course, it is best to use the include or require instructions to clearly separate each link.
The 5 steps of the Smarty program mentioned in the previous section, main. PHP will help us do the first three steps first, and the subsequent module program only needs to do the last two steps.
Start with variables
How to use variables
From the example in the previous chapter, we can clearly see that we use the two marking symbols <{ and }> to wrap variables. The default marking symbols are { and }, but for the sake of Chinese coding 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 in front (this is different from ordinary template engines). The marking symbols are a bit like

in PHP (in fact, they will be replaced by this), so the following template variable writing methods are feasible:
1. <{$var }>
2. <{ $var }>
3. <{$var
}>
In Smarty, variables are global by default, which means you only need to specify them once. If specified more than twice, the variable content will be based on the last specified one. Even if we load an external sub-template in the main template, the same variables in the sub-template will also be replaced, so we don't have to do another parsing action for the sub-template.
In the PHP program, we use Smarty’s assign to place variables in the template. The usage of assign has been written a lot in the official manual, and the usage is as shown in the example in the previous section. However, when repeating blocks, we must do some manipulation of the variables before assigning the variables to the template. This will be discussed in the next chapter.
Modify your variables
We mentioned above that the appearance of Smarty variables is determined by the template, so Smarty provides many functions for modifying variables. The method used is as follows:
<{Variable|Modified function}>
<{Variable|Modified function: "Parameters (not necessary, considered Depends on the function)"}>
The example is as follows:
<{$var|nl2br}>
<{$var|string_format:"%02d"}>
Okay, then why do you need a template? Determine the appearance of variables by yourself? First, take a look at the HTML below. This is part of a shopping cart checkout screen.

Total amount: 21,000 yuan
The template of a general template engine may be written like this:

Total amount: {format_total} yuan
Their PHP program should be written like this:
$total = 21000;
$tpl->assign( "total", $total);
$tpl->assign("format_total", number_format($total));
?>
The Smarty template can be written like this: (For the number_format modification function, please go to Smarty official website Web page download)

Total amount: <{$total|number_format:""}> yuan
Smarty's PHP program only needs to write like this:
$total = 21000;
$tpl->assign("total", $total);
?>
So in Smarty we only need to specify it once variables, and leave the rest to the template to decide. Do you understand this? This is the benefit of letting the template decide how the variables will look on their own!
Control the content of the template
Duplicate blocks
In the Smarty template, we have two ways to repeat a block: foreach and section. In the program, we have to assign an array, which can contain an array of arrays.Just like the following example:
First, let’s look at how the PHP program is written:
test2.php:
require "main.php";
$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("test2.htm");
?>
The template is written as follows:
templates/test2.htm:
< ;html>


Test duplicate blocks

 
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}>


After executing the above example, we found that whether it is foreach or section, the two execution results are the same. So what is the difference between the two?
The first difference is obvious, that is, foreach uses a nested processing method to present the two-level array variables we assign, while section uses "main array [loop name]. sub-array index" to assign the entire array presented. It can be seen that the foreach in Smarty's template is the same as the foreach in PHP; and section is a description developed by Smarty in order to process the array variables listed above. Of course, the function of section is more than that. In addition to the nested data presentation discussed in the next section, the official manual also provides several application examples of section.
But it should be noted that the array index thrown to section must be a positive integer starting from 0, that is, 0, 1, 2, 3, .... If your array indexes are not positive integers starting from 0, you will have to use foreach instead to present your data. You can refer to this discussion in the official forum, which discusses the usage of section and foreach .
Presentation of nested data
The most troublesome thing in template engines is probably the presentation of nested data. Many famous template engines will specifically emphasize this point, but this is child's play for Smarty.
The most common nested information is the discussion topic area in the discussion program.Assume that the results to be presented are as follows:
Announcement Area
Site Service Announcement
Literature Area
Introduction to Good Books
Shared Articles
Computer Area
Hardware Peripherals
Software Discussion
In the program, we first take static data as an example:
test3.php:
require "main.php";
$forum = array(
array("category_id" => 1, "category_name" => "Announcement Area",
"topic" => array(
array("topic_id" => 1, "topic_name" => "Website Announcement")
)
),
array("category_id" => 2, "category_name" => "Literature Zone",
"topic" => array(
array("topic_id" => 2, "topic_name" => "Introduction to good books"),
array("topic_id" => 3, "topic_name" => " Enjoy all the wonderful articles")
)
),
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("test3.htm");
?>
The template is written as follows:
templates/test3.htm:

< head>
Nested loop test



<{section name=sec1 loop=$forum}>



<{section name=sec2 loop=$forum[sec1].topic}>



<{/section}>
<{$forum[sec1].category_name} >
< ;/td>
<{$forum[sec1].topic[sec2].topic_name}>



The execution result is just like the example given by the author.
So, in the program, we only need to find a way to stuff the repeated values ​​into the array layer by layer, and then use <{First level array [Loop 1]. Second level array [Loop 2]. The third level array [Loop 3]. ... .Array Index}> This way to display the value in each nested loop. As for what method to use? We will mention it again when using the database in the next section.
Convert the data in the database
The above mentioned how to display nested loops, but in actual application our data may be grabbed from the database, so we have to find a way to turn the data in the database into the above-mentioned multiple array form. Here the author uses a DB category to capture the data in the database. You can use your favorite method.
We only modify the PHP program, and the template is still the one above (this is the benefit of the template engine~). The $db object is assumed to have been created in main.php, and the captured data is the example above.
test3.php:
require "main.php";
// Create the first level array first
$category = array();
$db->setSQL($SQL1, @#CATEGORY @#);
if (!$db->query(@#CATEGORY@#)) die($db->error());
// Grab the data of the first layer of loop
while ($item_category = $db->fetchAssoc(@#CATEGORY@#))
{
// Create a second-level array
$topic = array();
$db->setSQL(sprintf($SQL2, $item_category[ @#category_id@#]), @#TOPIC@#);
if (!$db->query(@#TOPIC@#)) die($db->error());
// Fetch Second-level loop data
while ($item_topic = $db->fetchAssoc(@#TOPIC@#))
{
// Push the captured data into the second-level array
array_push($topic, $item_topic);
}
//Specify the second-level array as a member of the data captured by the first-level array
$item_category[@#topic@#] = $topic;
// One layer of data is pushed into the first layer array
array_push($category, $item_category);
}
$tpl->assign("forum", $category);
$tpl->display("test3. htm");
?>
After fetching a piece of information from the database, what we get is an array containing the data. Through the while statement and the array_push function, we push the data in the database into the array one by one. If you only use a single layer of loops, just remove the second layer of loops (the red part).
Decide whether the content is displayed
To decide whether to display the content, we can use the if syntax to make the selection. For example, if the user has logged in, our template can be written like this:
<{if $is_login == true}>
Display the user operation menu
<{else}>
Display the username and password input Form
<{/if}>
It should be noted that there must be at least one space character on both sides of the "==" sign, otherwise Smarty will not be able to parse it.
For general application of if syntax, you can refer to the official instructions for use, so I will not introduce it in detail here. However, the author found an interesting application: I often see a table like this generated in the program: (The number represents the order of the data set)
1 2
3 4
5 6
7 8
This is what the author calls it "Horizontal repeating table". Its characteristics are different from traditional vertical repetition. The repeated tables we saw in the previous sections are all from top to bottom, with only one piece of data in one column. The horizontally repeated table can generate n pieces of data in one column horizontally, and then change to the next column until the entire cycle ends. To achieve such a function, the simplest way is just to match section and if.
Let’s take a look at the following example:
test4.php:
require "main.php";
$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(@# test4.htm@#);
?> ;/head>



<{section name=sec1 loop= $my_array}>

<{if $smarty.section.sec1.rownum is div by 2}>
< ;/tr>

<{/if}>
<{/section}>

<{$my_array[sec1].value}>


The key point is the Smarty variable $smarty.section.sec1.rownum. 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> Change the columns of the table (Attention! is in front in back). So the number 2 is the number of data items we want to display in a column. You can use this to change other different presentation methods.
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 respectively; include_php is rarely used by the author, and the usage method can be found in the official manual, which will not be discussed here. Narrative.
When using include, we can pre-load sub-templates or dynamically load sub-templates. Pre-loading is usually used when there are common file headers and copyright declarations; dynamic loading can be used on unified frame pages to further achieve replaceable Skin like Winamp. Of course, we can also mix these two, depending on the situation.
Let’s take a look at the following example:
test5.php:
require "main.php";
$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 @#);
?>
Template 1 is written as follows:
templates/test5_1.htm:



<{$title}>


<{include file="test5_2.htm"}>< ;br />
<{include file=$dyn_page}>
<{include file="test5_4.htm" custom_var="content of custom variable"}>

< /html>
Template 2 is written as follows:
templates/test5_2.htm:
<{$content}>
Template 3 is written as follows:
templates/test5_3.htm:
This is the content of template 3
Template 4 The writing method is as follows:
templates/test5_4.htm:
<{$custom_var}>
Note a few key points here: 1. The location of the template is based on the previously defined template_dir; 2. All sub-templates included , its variables will also be interpreted; 3. In include, you can use "variable name = variable content" to specify the variables included in the imported template, just like template 4 above.

The above is an introduction to smart flash recovery, an introduction to Smarty for beginners learning PHP, including the content of smart flash recovery. I hope it will be helpful to friends who are interested in PHP tutorials.


Related labels:
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template