Home  >  Article  >  Backend Development  >  Getting Started with Smarty for Newbies Learning PHP_PHP Tutorial

Getting Started with Smarty for Newbies Learning PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:58:041704browse

PHP designers who are new to 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 the author believes that 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 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 are 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 assign job. . 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 assigned directly 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 After inserting the variables, parse the template through the parse() method, 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.

Use 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


Most of these blocks will be used in PHP programs with if or for, while To control their display status, although the template looks much simpler, as soon as the template is changed to a different display mode, 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, the location may be similar to this: " d:appservwebdemo ".

Under Linux, the location may be 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 they don't have to worry about whether Smarty is installed on the host.

Folder settings of the program

Take the author installing 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 of 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 = @#}>@#;
?>




The purpose of setting it in the above way is that if the program needs to be transplanted to other places, just change __SITE_ROOT. (This is for reference 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 name is, but it is convenient for visual designers to develop, so I still use .htm as the main extension.)

templates/test.htm:



<{$title}>


<{$content}> ;






Now we need to display the above template and add the page title ($title) To replace the content ($content), please name the following file content test.php and place it in the main folder:

test.php:

require "main.php";
$tpl->assign("title", "Webpage title for testing");
$tpl->assign("content", "Webpage content for testing" ");
// The above two lines can also be replaced by this line
// $tpl->assign(array("title" => "Testing webpage title", "content" => ; "Web page content for testing"));
$tpl->display(@#test.htm@#);
?>




Please open your browser and enter http://localhost/demo/test.php to try (the URL depends on your environment). You should see the following screen:



Then Under templates_c, we will see a strange folder (%%179). If we click on it, it will also be a strange folder (%%1798044067), and there is a file in it:

templates_c/% %179/%%1798044067/test.htm.php:





< title>_tpl_vars[@#title@#]; ?>


_tpl_vars[@#content@#]; ?>






Yes, this is the file compiled by Smarty. It converts our variables in the template into PHP syntax for execution. Next time the same content is read, Smarty will directly grab this file and execute it.

Finally, let’s sort out the entire Smarty program writing steps:

Step 1. Load the Smarty template engine.

Step 2. Create Smarty object.

Step 3. Set the parameters of the Smarty object.

Step 4. After processing the variables in the program, use Smarty’s assign method to place the variables into the template.

Step 5. Use Smarty’s display method to display 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: includes, modules . In fact, this was built by the author after imitating the architecture of XOOPS, because XOOPS is one of the few website building programs that uses the Smarty template engine among the programs that the author has come into contact with. The so-called watermelon is close to the big edge. Although the program structure of the author is not one percent as strong as XOOPS, at least it still has the support of XOOPS when it is seen by others.

includes This folder is mainly used to place some function and sql files, so that they can be introduced in main.php, as follows:

main.php:


include "class/Smarty.class.php";
define(@#__SITE_ROOT@#, @#d:/appserv/web/demo@#); // Finally No slash
// Based on the position of main.php
require_once "includes/functions.php";
require_once "includes/include.php";
$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 it will not be Programs are scattered everywhere, and the overall structure is clear at a glance.

We also mentioned above that main.php is the main core of the entire program. Whether it is constant definition, external program loading, shared variable creation, etc., it all starts here. So all subsequent modules only need to include this file. Therefore, during program planning, it is necessary to think carefully about what should be placed in main.php; 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, main.php will help us do the first 3 steps first, and the subsequent module program only needs to do the last two steps. That's it.

Start with variables

How to use variables

From the example in the previous chapter, we can clearly see that we use the two symbols <{ and }> Symbols 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 is All are feasible:

1. <{$var}>

2. <{ $var }>
in 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 that 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 (optional, depending on the function)"}>
The example is as follows:

<{ $var|nl2br}>

<{$var|string_format:"%02d"}> ;
Okay, then why let the template decide how the variables appear? First look at the HTML below. This is part of a shopping cart checkout screen.



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



Total amount: {format_total} yuan
Their PHP program It should be written like this:


$total = 21000;
$tpl->assign("total", $total);
$tpl- >assign("format_total", number_format($total));
?>




And Smarty’s template can be written like this: (number_format modification function Please go to Smarty official website to download)



Total amount: <{$total|number_format:""}> Just write this in Yuan
Smarty's PHP program:


$total = 21000;
$tpl->assign("total", $total);
?>




So in Smarty we only need to specify the variable once, and the rest is done Just leave it 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:




Test repeated blocks


 <br>Use foreach to render array1 <br><{foreach item=item1 from=$array1}> <br><{$item1}> <br><{/foreach}> <br>Use section to present array1 <br> <{section name=sec1 loop=$array1}> <br><{$array1[sec1]}> <br><{/section}> <br>Use foreach to present array2 <br> <{foreach item=index2 from=$array2}> <br><{foreach key=key2 item=item2 from=$index2}> <br><{$key2}>: <{$ item2}> <br><{/foreach}> <br><{/foreach}> <br>Use section to present array1 <br><{section name=sec2 loop=$array2}&gt ; <BR>index1: <{$array2[sec2].index1}> <br>index2: <{$array2[sec2].index2}> <br>index3: <{$array2[sec2] .index3}> <br><{/section}> <br>







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" The entire array can be displayed. 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.

However, 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

Probably the most troublesome thing in the template engine is the presentation of nested data. Many famous template engines will specifically emphasize this point, but this is not important for Smarty It's just a child's play.

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

Station Announcement

Literature Zone

Introduction to Good Books

Appreciation of Wonderful Articles

Computer Zone

Hardware Peripheral

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" => "Site 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" => "Sharing 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");
?>




template The writing method is as follows:

templates/test3.htm:



Nested loop test



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


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


<{/section}>
<{/section}>
<{$forum[sec1].category_name}>

<{$forum[sec1].topic[sec2].topic_name}>







The execution result is just like the example given by the author.

Therefore, 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 Convert the database data 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 above example.

test3.php:


require "main.php";
// Create the first level array first
$category = array();
$db->setSQL($SQL1, @#CATEGORY@#);
if (!$db->query(@#CATEGORY@#)) die($db- >error());
// Fetch the data of the first level 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());
// Grab the data of the second layer loop
while ( $item_topic = $db->fetchAssoc(@#TOPIC@#))
{
// Push the captured data into the second layer 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;
//Push the first level data into the first level array
array_push($category, $item_category);
}
$tpl->assign("forum", $category);
$tpl->display("test3.htm");
?>




After grabbing a piece of information from the database, we get is an array containing the data. Through the while statement and 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).

Determine 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}>
Show user operation menu
<{else} >
Display the form for entering account number and password
<{/if}>

It should be noted that there must be at least one space 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

The author calls this "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@ #);
?> ;

Horizontal repeating table test




<{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, output to change the columns of the table (note! 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; I rarely use include_php. You can check the official manual for usage instructions, which will not be described here.

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

<{include file=$dyn_page}>
<{include file="test5_4. htm" custom_var="Content of custom variable"}>






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 is written as follows:

templates/test5_4.htm:

<{$custom_var}>
Note here A few key points: 1. The location of the template is based on the previously defined template_dir; 2. In all included sub-templates, their 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317633.htmlTechArticlePHP designers who are new to template engines will find it difficult when they hear about Smarty. In fact, the author is no exception and dare not touch it. But later when analyzing the program architecture of XOOPS,...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn