Smarty Introduction
What is a stencil engine
I don't know when it started, and someone started to feel less satisfied with embedding the Server Script inside HTML. However, whether it is Microsoft's ASP or open source PHP, is the embedded server Script in the Web servers language. Therefore, it is also thought that if the application of logic (or business application logic) and Web page rendering (Layout) logic separation, it would be better?
In fact, this problem has long existed, from the beginning of the popular interactive Web page, whether the ASP or PHP users are both program developers and visual designer identity. But usually these users are not the program is strong, if you want both at the same time, it can kill a lot of brain cells ...
So the template engine was born! 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 functionality, while visual designers can focus on page layouts to make the web look more professional! Therefore, the template engine is suitable for the company's website development team to use, so that everyone can play their expertise!
In the author's contact with the template engine, according to the data presentation method is roughly divided into: the need to match the process of the template engine and completely by the template itself decided by the template engine two forms.
In the template engine that needs to be matched with program processing, the program developer must be responsible for the rendering logic of the variable, which means that he must handle the contents of the variable before outputting to the template before doing assign work. In other words, program developers still have to write a few more programs to determine the appearance of variables. and completely by the template itself to determine the template engine, which allows the variable directly assign to the template, so that visual designers in the design of templates to determine how the variable to render. Therefore, it may have another set of its own template program syntax (such as Smarty) to facilitate the control of variable rendering. But as a result, visual designers also have to learn how to use the template language.
The operating principle of the template engine, first we look at the following diagram:
The general template engine (such as Phplib) is in the creation of template objects to be resolved by the template, and then put the variable into, through the parse () this method to parse the template, and finally the page output.
For Smarty users, the program does not need to do any parse action, these Smarty will automatically help us do. And already compiled pages, if the template is not changed, Smarty automatically skip the compilation of the action, directly execute the compiled pages, to save the compile time.
Some concepts of using smarty
In the general template engine, we often see the concept of the region, the so-called block is probably like this:
<!--start:block name-->
Area content
<!--end:block name-->
Most of these blocks will be in the PHP program with if or for, while to control their display status, although the template looks more concise, but as long as a change in the display mode of different templates, PHP program is bound to change again!
In Smarty, everything is dominated by variables, and all the rendering logic allows the template to control itself. Because Smarty will have its own template language, so whether the block is to show or to repeat, are used Smarty template syntax (if, foreach, section) with variable content for rendering. This makes the impression that the template becomes a bit more complicated, but the advantage is that as long as the plan is right, the PHP program does not have to change one line.
From the above description, we can know that using smarty to master a principle: The application of the program logic and Web page rendering logic clearly separated. This means that there are not too many HTML code in the PHP program. In the program, just make sure those variables are in the template, and let the template decide how to render the variables (not even appear).
The foundation of Smarty
Install Smarty
First, let's decide where the program should be placed.
A location like this might be possible under Windows: "d:\appserv\web\demo\".
Linux may be similar to this position: "/home/jaceju/public_html/".
Download the latest Smarty kit from the official website of Smarty: Http://smarty.php.net.
After unlocking Smarty 2.6.0, you will see a lot of files, including a Libs folder. There should be 3 class.php + 1 DEBUG.TPL + 1 plugin folders + 1 Core folders in Libs. Then directly copy the Libs to your program Master folder, and then rename it to class. That's it? That's right! This installation method is relatively simple, suitable for users who do not normally own the host.
As for the Smarty Official Handbook, why do you want to introduce some of the more complex installation methods? Basically installed in the official way, it can be installed only once on the host, and then provided to all the designers under the host to develop different programs directly referenced, without repeatedly installing too many copies of the Smarty. And the author provides the way is suitable to bring the program to move over the program developers use, so do not worry about the host has not installed Smarty.
Program Folder settings
Take the author in the Windows installation Appserv as an example, the program's main folder is "d:\appserv\web\demo\". After installing the smarty, we will create the folder under the main folder:
Under Linux, remember to change the permissions of the Templates_c to 777. It is read-only cancellation under Windows.
The first small program written with Smarty
We set the Smarty path First, please name the following file as main.php and place it under the main folder:
main.php:
<?php
Include "class/smarty.class.php";
Define (@ #__SITE_ROOT @#, @ #d:/appserv/web/demo@#); Last no Slash
$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 the above method is that if the program is to be transplanted to another place, it can only be changed __site_root. (Here is the reference XOOPS)
Smarty template path is set, the program will follow this path to grasp the relative position of all templates (in the example is @ #d:/appserv/web/demo/templates/@#). Then we use the display () Smarty method to show our template.
Next we put a test.htm under the Templates folder: (extension name doesn't matter, but it's easy for visual designers to develop, the author is still based on. htm. )
Templates/test.htm:
<meta http-equiv= "Content-type" content= "text/html; Charset=big5 ">
<title><{$title}></title>
<body>
<{$content}>
</body>
Now that we're going to show the template above and replace the page title ($title) with the content ($content), name the following file as test.php and place it under the main folder:
test.php:
<?php
Require "main.php";
$tpl->assign ("title", "test page caption");
$tpl->assign ("content", "test page contents");
The two lines above can also be used as a substitute.
$tpl->assign ("title" => "test page title", "Content" => "test Web Content"));
$tpl->display (@ #test. htm@#);
?>
Please open the browser, input http://localhost/demo/test.php try (depending on your environment to determine the site), you should see the following screen:
And under the Templates_c, we'll see a strange folder (%%179), and then it's a weird folder (%%1798044067), and there's a file:
templates_c/%%179/%%1798044067/test.htm.php:
<?php/* Smarty version 2.6.0, created on 2003-12-15 22:19:45 * compiled from test.htm/?>
<meta http-equiv= "Content-type" content= "text/html; Charset=big5 ">
<title><?php echo $this->_tpl_vars[@ #title @#];?\></title>
<body>
<?php echo $this->_tpl_vars[@ #content @#];?\>
</body>
Yes, this is Smarty's compiled file. It transforms the variables we have in the template into PHP syntax to execute, and the next time we read the same content, the Smarty will grab the file and execute it directly.
Finally, we'll tidy up the whole Smarty program writing steps:
Step 1. Load the Smarty stencil engine.
Step 2. Create a Smarty object.
Step 3. Sets the parameters of the Smarty object.
Step 4. After the variables are processed in the program, the variables are placed into the template using the Smarty assign method.
Step 5. Use the Smarty display method to show the Web page.
How to arrange your program architecture
Above we see in addition to the Smarty required folder (class, Configs, Templates, Templates_c), there are two folders: Includes, modules. In fact, this is the author's imitation of the architecture of XOOPS, because XOOPS is the author of the process of contact, a few use Smarty template engine of the station program. The so-called watermelon edge, the author of such a program structure, although not XOOPS 1% strong, but at least for people to see when there is XOOPS backing.
Includes this folder is mainly used to place some function, SQL files, so that they can be introduced in main.php, as follows:
main.php:
<?php
Include "class/smarty.class.php";
Define (@ #__SITE_ROOT @#, @ #d:/appserv/web/demo@#); Last no Slash
Base 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 the program module, so will not throw the program everywhere, the overall architecture at a glance.
Above we also mentioned main.php, this is the main core of the entire program, whether it is the definition of constants, external program loading, shared variables, etc., are all started here. So the next module is just to include this file in it. Therefore, during program process planning, it is necessary to think about what should be put in the main.php, and of course it is better to separate each link clearly by using the include or require instructions.
Mentioned in the previous section of the Smarty program 5 steps, main.php will help us to do the first 3 steps, the following module program as long as the following two steps on it.
Starting from a variable
How to use variables
From the example in the previous chapter, we can see clearly that we use <{and}> to wrap the variables together. The preset symbol is {and}, but in order to Chinese code and JavaScript relationship, so the author or imitate XOOPS, will mark the symbol to replace. The name of the variable is exactly the same as the variable naming method for PHP, which has a $ font size (this is different from a generic template engine). The notation is a bit like the one in PHP
(In fact they are actually replaced with this), so the following template variables are written in a workable way:
1. <{$var}>
2. <{$var}> <!--and variables have spaces between them-->
3. <{$var
}> <!--The beginning of the mark and the end of the symbol is not the same line-->
In Smarty, the variable presets are global, which means you just have to specify one time. If you specify more than two times, the variable content will be given as the final designation. Even if we loaded the external child template in the main template, the same variable would be substituted in the template, so that we don't have to do another parse action on the child template.
And in the PHP program, we use the Smarty assign to put the variables into the template. The Official Handbook of Assign's usage has been written a lot, as the example in the previous section shows. But when we repeat blocks, we have to do something with the variable to assign the variable into the template, which is mentioned in the next chapter.
Modify your variables.
We mentioned above that the style of Smarty variable presentation is determined by the template itself, so Smarty provides a number of functions for modifying variables. The following methods are used:
<{variable | modifier}> <!--when the modifier does not have an argument-->
<{variable | modifier: parameter (not necessary, depending on function)}> <!--when the modifier has parameters-->
Examples are as follows:
<{$var |nl2br}> <!--change line characters in a variable to <br/>-->
<{$var |string_format: "%02d"}> <!--format variable-->
Well, why do you want the template to decide the style of the variable? First look at the bottom of the HTML, which is part of the checkout of a shopping cart screen.
<input name= "Total" type= "hidden" value= "21000"/>
Total Amount: 21,000 RMB
The template for a generic template engine might write this:
<input name= "Total" type= "hidden" value= "{total}"/>
Total amount: {format_total} yuan
In their PHP program, write this:
<?php
$total = 21000;
$tpl->assign ("Total", $total);
$tpl->assign ("Format_total", Number_format ($total));
?>
The Smarty template can be written like this: (Number_format modifier, please go to the Smarty website)
<input name= "Total" type= "hidden" value= "<{$total}>"/>
Total amount: <{$total |number_format: ""}> yuan
The Smarty PHP program is written as follows:
<?php
$total = 21000;
$tpl->assign ("Total", $total);
?>
So in Smarty we just specify a variable, and the rest is left to the template to decide. Do you know that? This is to allow the template to determine the advantages of the variable appearance!
Control the content of the template
Duplicate blocks
In the Smarty template, there are two ways to repeat a block: foreach and section. And in the program we're going to assign an array that can contain an array of arrays. Just like the following example:
First, let's look at how the PHP program is written:
test2.php:
<?php
Require "main.php";
$array 1 = Array (1 => "Apple", 2 => "Pineapple", 3 => "Banana", 4 => "ba Le");
$tpl->assign ("Array1", $array 1);
$array 2 = 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", $array 2);
$tpl->display ("test2.htm");
?>
And the template is written as follows:
Templates/test2.htm:
<html>
<head>
<meta http-equiv= "Content-type" content= "text/html; Charset=big5 ">
<title> Test Repeat blocks </title>
</head>
<body>
<pre>
Using foreach to render array1
<{foreach item=item1 from= $array 1}>
<{$item 1}>
<{/foreach}>
Use section to render Array1
<{section name=sec1 loop= $array 1}>
<{$array 1[sec1]}>
<{/section}>
Using foreach to render array2
<{foreach item=index2 from= $array 2}>
<{foreach key=key2 item=item2 from= $index 2}>
<{$key 2}>: <{$item 2}>
<{/foreach}>
<{/foreach}>
Use section to render Array1
<{section name=sec2 loop= $array 2}>
INDEX1: <{$array 2[sec2].index1}>
Index2: <{$array 2[sec2].index2}>
INDEX3: <{$array 2[sec2].index3}>
<{/section}>
</pre>
</body>
</html>
After performing the above example, we found that either foreach or section two execution results are the same. So what's the difference between the two?
The first difference is obvious: foreach is going to render the two-tier array variables we assign in a nested way, and the section will present the entire array as a "primary array [circular name]." Sub-array index. As a Smarty, the foreach in the template is the same as the foreach in PHP, while the section is Smarty to handle the narrative developed for the array variables listed above. Of course, the function of the section is not only so, in addition to the nest-like data presented in the next sections, the Official Handbook also provides several examples of section application.
Note, however, that the array index that is dropped to the section must be a positive integer starting with 0, i.e. 0, 1, 2, 3, .... If your array index is not a positive integer starting with 0, then you have to use foreach instead to present your data. You can refer to this discussion in the official discussion area, which explores the use of section and foreach.
Presentation of nest-like data
The most nerve-racking part of the template engine is the appearance of the nest-shaped data, which many famous template engines have deliberately emphasized, but this is a Smarty for the world.
The most common form of the nest-like data, even on the forums program in the discussion subject area bar. Suppose the results to be rendered are as follows:
Bulletin board
Station Service Announcement
Literature Zone
Introduction to Good Books
Chiven
Computer Zone
Hardware Peripherals
Software discussion
In the program we first take static data as an example:
test3.php:
<?php
Require "main.php";
$forum = Array (
Array ("category_id" => 1, "Category_name" => "Bulletin Area",
"topic" => Array (
Array ("topic_id" => 1, "topic_name" => "station Service Bulletin")
)
),
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" => "Chiven")
)
),
Array ("category_id" => 3, "Category_name" => "Computer Zone",
"topic" => Array (
Array ("TOPIC_ID" => 4, "topic_name" => "Hardware Peripherals"),
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:
<title> nested loop test </title> ;
<body>
<table width= " 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>&N Bsp
<td width= > </td>
<td width= "164" ><{$forum [sec1].topic[ sec2].topic_name}></td>
</tr>
<{/section}>
<{/SECTION}&G t;
</table>
</body>
The results of the execution are the same as the example I cited.
So, in the program, we just have to find a way to cram the duplicate values into the array, and then use the <{first level array [Loop 1]. The second-tier array [loop 2]. The third-tier array [Loop 3] ... The array index}> this way to display the values in each nested loop. As for what method? We'll talk about it when we use the database in the next section.
converting data in a database
The above mentioned how to display the nested loop, and in fact, when the application of our data may be crawled from the database, so we have to find a way to put the data of the database into the form of the above multiple arrays. Here I use a DB category to crawl the data in the database, you can use your own way.
We only modify the PHP program, the template or the top one (this is the advantage of the template engine ~), which $db this object hypothesis has been established in the main.php, and the captured data is the above example.
test3.php:
<?php
Require "main.php";
First-tier arrays are created first
$category = Array ();
$db->setsql ($SQL 1, @ #CATEGORY @#);
if (! $db->query (@ #CATEGORY @#)) Die ($db->error ());
Capturing the data of the first layer cycle
while ($item _category = $db->fetchassoc (@ #CATEGORY @#))
{
Creating a second-tier array
$topic = Array ();
$db->setsql (sprintf ($SQL 2, $item _category[@ #category_id @#]), @ #TOPIC @#);
if (! $db->query (@ #TOPIC @#)) Die ($db->error ());
Data to crawl the second-tier cycle
while ($item _topic = $db->fetchassoc (@ #TOPIC @#))
{
Push the crawled data into the second-tier array
Array_push ($topic, $item _topic);
}
Specifies a second-tier array as a member of the data crawled by the first-tier array
$item _category[@ #topic @#] = $topic;
Push the first level of data into the first-tier array
Array_push ($category, $item _category);
}
$TPL->assign ("forum", $category);
$tpl->display ("test3.htm");
?>
After the database grabs a piece of data, we get an array that contains the data for that pen. Through the while narration and the Array_push function, we cram the data from the database into the array in a lump sum. If you only use a single layer loop, remove the second layer of the loop (the red part).
Determines whether content is displayed
To decide whether or not to display content, we can use the syntax of if to make a choice. For example, if the user has logged in, our template can be written like this:
<{if $is _login = = true}>
Show User Action menu
<{else}>
Display the form for entering account numbers and passwords
<{/if}>
Note that the "==" number must be left at least one spaces each side, or Smarty will not be able to resolve.
If syntax general application can refer to the official use of the instructions, so the author here on the unknown added. But the author found an interesting application: often see a program to produce such a table: (Numbers represent the order of the DataSet)
1 2
3 4
5 6
7 8
This author calls it "horizontal repeating table". Its features are different from the traditional longitudinal repetition, and the repeating forms we see in the previous sections are all from the top down, with one column of data. A horizontal repeating table can be used to produce n-data in a column horizontally, and then another column until the entire loop ends. To achieve this, the easiest way to do this is to use only the section and the If collocation.
Let's take a look at the following example:
test4.php:
<?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@#);
?>
The template is written as follows:
Templates/test4.htm:
<title> transverse repeating table test </TITLE>&NB Sp
<body>
<table width= " border=" 1 " cellspacing=" 0 " cellpadding=" 3 ">
<tr>
<{section name=sec1 loop= $my _array}>& nbsp
<td><{$my _array[sec1].value}></td>
<{if $smarty. Section.sec1.rownum is div by 2}>
</tr>
<tr>
<{/if}>
<{/section}>
</tr>
</table>
</body>
The point is $smarty. section.sec1.rownum this smarty variable, which gets the index value starting at 1 in the section loop, so when rownum can be removed by 2, it outputs </tr><tr> Make a Table change column (note!) Is </tr> in front <tr> in the back). So the number 2 is the number of pens we want to render in a column. You can change different ways of presenting.
Load External Content
We can load PHP code in the template or another template, respectively, using include_php and include these two Smarty template syntax; include_php less use, the use of the way you can query the Official handbook, no longer described here.
When using include, we can preload the child templates or dynamically load the child templates. Pre-loading is commonly used in common file headers and copyright announcements, while dynamic loading can be used in a unified frames page, and further achieve such as Winamp can be replaced Skin. Of course these two we can also mix, depending on the situation.
Let's take a look at the following example:
test5.php:
<?php
Require "main.php";
$tpl->assign ("title", "Include test");
$tpl->assign ("content", "This is the 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:
<meta http-equiv= "Content-type" content= "text/html; Charset=big5 ">
<title><{$title}></title>
<body>
<{include file= "test5_2.htm"}><br/>
<{include file= $dyn _page}>
<{include file= "test5_4.htm" custom_var= "contents of custom Variables"}>
</body>
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}>
Here are a few points to note: 1. The position of the template is based on the previously defined template_dir; 2. In all included templates, the variables are also interpreted. ; 3. The include variable name = variable content can be used to specify the variables contained in the template that is included, as in template 4 above.
The logical layer and presentation layer of the MVC development pattern in PHP has a variety of template engines to choose from, but when the official engine Smarty is born, the choice changes. Its idea and realization are quite "avantgarde". This paper mainly discusses the different characteristics of smarty to other template engines, briefly introduces the installation and use of the engine, and compares the speed and ease of smarty and phplib template with a small test case.
One, MVC needs template
MVC was the first design pattern to be summed up in the development of Smalltalk language, and MVC represented "model", "View" and "control" respectively, so that different development roles could be involved in large and medium-sized projects. In the development of Web applications, the following diagram can be used to represent the relationships among the concepts.
The diagram shows a simple Web application in which the user sees the information on the database server, but before it is processed by the application server. What developers are responsible for is building data structures, processing the logic of data, and methods of representing data.
When the 96 CGI became popular in China, early web programmers began to learn from HTML, and it was not difficult to print a row of HTML in Perl, but as the network sped up, the page size jumped 10 times times from the original 20 or 30 K. Writing CGI programs creates an urgent requirement: Separate Perl and HTML source code. Thus, social progress is embodied in the Division of labor within the development group. Because art and programmers are not very familiar with each other's work, in the process of cooperation need to use a "language" to communicate.
This language is not our mother tongue or English, the term is called "template", logic and representation depend on it. It is an expression that combines HTML and scripting language features. In this way, the presentation layer can display data that has been processed by the logical layer in the format that the user wants. If you have the development experience of MFC under Windows platform, you will be familiar with the encapsulation of document/document Template/view, this is a typical MVC example. For Web applications, individuals think that the ejb/servlets/jsp in Java EE is the most powerful, and of course there are simple and graceful structs. Another well-known realization is com/dcom+asp, which is the most used in our country.
By comparing several MVC implementations in a Web application, you can get a concept of a template: A set of HTML-inserted scripts or scripting HTML that represents the changed data through the inserted content. The following is an example of a template file, which is processed to display "Hello, world!" in the browser.
<title> $greetings </title>
<body>
$greetings
<body>
Here for the moment to omit the treatment, in the following special comparative discussion.
Second, why Choose Smarty?
For PHP, there are a number of template engines to choose from, such as the first phplib template and the Up-and-comer fast template, after several upgrades, has been quite mature and stable. If you are satisfied with the current template engine, then ... Also look down and believe that you as a free software enthusiast or for the pursuit of efficiency and elegance of the developers, the following Smarty introduced how much will be somewhat interesting.
In addition to the impact of personal preferences, I have tended to use official standards for implementations such as Apache's XML engine axis. The advantage is that you get as good a compatibility as possible (for example, early MFC's compatibility with WIN3X is better than other application frameworks, but now all versions are perfect). I have been using the integrated Template eXtension in PEAR before Smarty released. This engine is almost compatible with phplib template, Fast template, from the syntax of the template to the processing of the template expatiating: All the templates are read into memory and then called the Parse () function, replacing the preset tags with the data.
Let's see how smarty is doing. After receiving the request, first decide whether to request the URL for the first time, if it is, the template file required for the URL "compiled" into a PHP script, and then redirect; if not, it means that the template for the URL has been "compiled", checking that you do not need to recompile to immediately redirect , the recompile condition can be set to its own fixed time limit, and the template file is modified by default.
What, does it look a little familiar? Come to think of it--this is not the principle of JSP! It is true that this "compilation" is unthinkable in an interpretative scripting engine such as PHP, but is Java not also interpreted by the JVM? This is called "nothing can not be done, only unexpected."
Now that we've talked about Java, let's comment on the future of PHP. The official PHP website announced the release of the PHP5.0 version by the end of 2003. This version has many new features: exception handling, namespaces, more object-oriented, and more. It can be said that more and more to the Java, Smarty is also one of the new features, making PHP more suitable for large and medium-sized project development. But it seems that the reason I chose it--the deft use of it--is getting far. But in terms of the life cycle of a software, PHP is in the growth period, the developer gives it more functions, in order to be able to do business applications is more advantages than disadvantages. As a loyal user of PHP, you certainly don't want PHP to always be blamed for "lack of capacity"?
Why choose Smarty just because it looks like a JSP? There are, of course, more good reasons. First of all, in addition to the cost of the first compilation is relatively high, as long as the template file is not modified, compiled cache script is available at any time, save a lot of parse (), and then smarty like PHP has a rich library of functions, from counting words to automatic indentation, Text wrapping and regular expressions can be used directly, if not enough, such as the need for data results set paging display function, Smarty also has a strong ability to expand, through the form of plug-ins can be expanded.
Facts speak louder than words. I designed a test program that compares Smarty and phplib template with speed and development difficulty, and phplib template because there is a phplib in Patrick's article, "Choosing the right template in the PHP world." Template to fast template competition, the result phplib template swept, this makes smarty have a good opponent. Before testing, talk about the issues you need to be aware of during the installation process.
Iii. problems that may be encountered
On the official website of Smarty, there is a detailed user manual that allows you to select online HTML and PDF versions. There is no longer a reference to what is already in the manual, but an explanation of the problems that may be encountered in the first use.
The first question is fatal: Does the hint say you can't find the file you want? Not everyone writes the application according to the Smarty default directory structure. This needs to be manually specified, assuming the directory structure is as follows:
You need to specify the directory structure in index.php:
$smart->template_dir = "smarty/templates/";
$smart->compile_dir = "smarty/templates_c/";
$smart->config_dir = "smarty/configs/";
$smart->cache_dir = "smarty/cache/";
The first problem was solved, followed by the second: how can I use the beautiful template I just created with Dreamweaver? It is not a problem with the template file, but because the default tag delimiter for Smarty is {}, and unfortunately JavaScript certainly contains this tag. Fortunately we can use any character as a separator, plus these two sentences:
$smart->left_delimiter = "{/";
$smart->right_delimiter = "/}";
This installation is basically done, no problem.
Iv. contrast and analogy
First conceive the design of the test. The main factor of comparison is speed. In order to carry out the speed test, the arithmetic mean is adopted. In the test page, repeat the page generation n times, and then compare the total page generation time. Another important factor is ease of use (as far as extensibility does not have a result to compare), so the template used cannot be too small. I use the page of my personal homepage, an HTML file generated with Firework+dreamweaver, about 7K in size. One of the variable settings also take the most commonly used blocks, in the phplib template called block, and Smarty is called section. Don't underestimate the difference of the name, the ease of use standard is divided into two: template file and script file syntax is concise and easy to use.
Let's drill down to the test. First look at the syntax of the two template files: the blue bar to the left is the Phplib template template, the right belongs to Smarty. Personal preference is not the same, so there is no comment here. Focus on the processing statements in the script, first look at the Phplib template:
$tpl->set_file (' phplib ', ' bigfile.htm ');
$tpl->set_block (' phplib ', ' Row ', ' rows ');
for ($j = 0; $j < $j + +) {
$tpl->set_var (' tag ', "$j");
$tpl->parse (' Rows ', ' Row ', true);
}
$tpl->parse (' Out ', ' phplib ');
$tpl->p (' out ');
Here are the Smarty:
$smart->assign (' Row ', $row);
$smart->display (' bigfile.htm ');
Smarty only used tags and row two variables, and phplib template more templates file handler, there is a baffling out. To tell the truth of this out I did not know why to exist when I learned, now look, or awkward. Why smarty less so much processing statements? The answer is that the work is done by the engine. If you like to delve into the source program, you can find a function called _compile_tag () in the Smarty_compiler.class.php, which is responsible for converting the section label into a PHP statement. This is not a common label, it has parameters and data, save the workload of scripting, and the workload on the template label is not large, you can determine the ease of use on the Smarty one domain.
It's our turn to focus on the speed, after all, for a skilled web developer, it is only a matter of time to master the tools of the difficult, not to mention the template engine this learning curve of the smooth technology. Speed is the life of a Web application, especially if the template engine is used on a site with a large number of concurrent accesses. Before the test began, I felt that phplib template would win this part because it had undergone many upgrades and had almost no bugs, and Smarty's engine was too big to have two files like its opponents.
Sure enough, the test results are as follows, Phplib template has a 25% speed advantage:
But not all the time, I hit the refresh again, this time I got a different result:
The phplib basically did not change, but the smarty increased by 25%. Continuing to refresh, the results are similar to the second: Smarty is nearly 10% faster than Phplib template. I think this is the principle that the compiler is faster than the explanatory type. Smarty engine itself is very large, coupled with the template to compile into PHP files, of course, the speed is not as small as the phplib template. But this is only the first time. The second time the request was received, Smarty found that the template had been compiled, and the most time-consuming step was skipped, and the opponent had to find and replace the job in a step-by-steps manner. This is the compiler principle of the classic "Space Change Time" example.
V. Conclusion
The conclusion is that if you have fallen in love with smarty, what are you waiting for? Certainly not that it's omnipotent, just as I use the MVC pattern to write my personal site, instead of reducing the workload, but always for the coupling between different levels.
What does Smarty do for you? A classic example of a handbook: weather forecasting websites. I also think of one: the stock market. The use of Smarty on this site will be due to the frequent recompilation and low efficiency, or phplib template more suitable.
This article is not meant to compare the two engines, but to illustrate the advantages of smarty. The most significant thing about using it is that it is part of the new PHP system, as an independent force, except. NET and Java one, there are other options for large and medium web development. For the GNU project, its significance is tantamount to Liu Deng's army leaps into the Dabie mountains.