Beginner Learn PHP Smarty Primer

Source: Internet
Author: User
Tags foreach end execution functions sql variables php and variable
The PHP designer, who just started contacting the template engine, will find it hard to hear Smarty. In fact, the author is no exception, did not dare to touch. But later, when parsing XOOPS's program architecture, it was not difficult to begin to discover Smarty. As long as the Smarty Foundation work well, in general application is already quite enough. Of course, the foundation can play well, the next advanced application is not afraid.
  
The main purpose of this article is not to delve into the use of Smarty, which has been fully written in official usage notes. I only write down some of my own use of the experience, so that want to understand Smarty but not its door into the friends, you can get some inspiration. Because the content of this article is not very in-depth, the use of Smarty's friends may feel easier.
  
At present this article has been revised for the third time, I would like to add some material to come in; however, due to the relationship between time, many Smarty advanced techniques I did not study very thoroughly, so also dare not to take out clowning, but I believe this article should be able to meet most of the beginners want to learn Smarty Of course this article has the wrong place also welcome to inform, the author will be corrected in the next amendment.
  
  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 (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 <?php and?> in PHP (in fact they are actually replaced), 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:
  
<meta http-equiv= "Content-type" content= "text/html; Charset=big5 ">
<title> Test Repeat blocks </title>
<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}&gt: <{$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>
  
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 cycle test </title>
<body>
<table width= "border=" 0 "align=" center "cellpadding=" 3 "cellspacing=" 0 ">
<{section name=sec1 loop= $forum}>
<tr>
&LT;TD colspan= "2" ><{$forum [sec1].category_name}></td>
</tr>
<{section name=sec2 loop= $forum [sec1].topic}>
<tr>
&LT;TD width= > </td>
&LT;TD width= "164" ><{$forum [sec1].topic[sec2].topic_name}></td>
</tr>
<{/section}>
<{/section}>
</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> Horizontal repeating table test </title>
<body>
<table width= "border=" 1 "cellspacing=" 0 "cellpadding=" 3 ">
<tr>
<{section name=sec1 loop= $my _array}>
<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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.