Beginners Learn PHP smarty Introductory _php Tutorial

Source: Internet
Author: User
Tags constant definition learn php smarty template
PHP designers, who are just beginning to touch the template engine, will find it hard to hear Smarty. In fact, the author is no exception, touch all dare not touch a bit. But later in the anatomy of XOOPS's program architecture, it is not difficult to begin to discover Smarty. As long as the Smarty Foundation work is good, in general application is already quite enough. Of course, the foundation can play well, the back of the advanced application will not be afraid.

The main purpose of this article is not to delve into the use of Smarty, which has been fully written in the official use notes. The author only here to write down some of their own use of the experience, let want to understand Smarty but not its door into the friend, can get some enlightenment. Because the content of this article is not very deep, friends who will use Smarty may find it a little simpler.

At present, this article has been revised for the third time, I would like to add some material in, but due to the time of the relationship, many Smarty advanced techniques I did not study very thoroughly, so also dare not to come out disgraced, but I believe this article should be able to meet most want to learn Smarty beginners. Of course, this article has the fallacy of the place is also welcome to inform, the author will be corrected in the next revision.

Smarty Introduction

What is a template engine

I don't know when it started, and someone started to feel less satisfied with the HTML embedded in the Server Script. However, whether it is Microsoft's ASP or open source PHP, is the embedded Server Script in the Web server-side language. Therefore, it is thought that if the application logic (or business application logic) and Web page rendering (Layout) logic separation, is it better?

In fact, this problem has long existed, from the beginning of the interactive Web page, whether it is the user of ASP or PHP is both a program developer and visual designer two identities. But usually these users are not program strong is the art of strong, if you want to both at the same time, that can die a lot of brain cells ...

So the template engine was born! The purpose of the template engine is to achieve the above mentioned logical separation function. It allows the programmer to focus on the control of the data or the function, while the visual designer can focus on the page layout and make the page look more professional! So the template engine is well suited to the company's website development team, so that everyone can play their expertise!

In terms of the author's contact with the template engine, according to the data presentation method is roughly divided into: need to match the program processing template engine and completely by the template itself decided by the template engine two forms.

In a template engine that needs to be processed with the program, the programmer must be responsible for the rendering logic of the variable, that is, he must handle the contents of the variable before outputting it to the template in order to do assign work. In other words, program developers have to write more programs to determine the appearance of variables. The template engine, which is entirely self-determined by the template itself, allows the variable to be assign directly into the template, allowing the visual designer to determine how the variable should be presented when designing the template. Therefore, it may have another set of its own template program syntax (such as Smarty), to facilitate the control of the rendering of variables. But in this way, visual designers also have to learn how to use the template language.

The working principle of the template engine, first we look at the following operation diagram:

The general template engine (such as Phplib) is to parse the template when the template object is created, and then put the variable into the parse () this method to parse the template, and finally the page output.

For Smarty users, there is no need to do any parse action in the program, these Smarty will help us do it automatically. and has compiled the Web page, if the template does not change, Smarty will automatically skip the compilation of the action, directly execute the compiled page, to save the compilation time.

Some concepts of using smarty

In the general template engine, we often see the concept of the region, so-called chunks are likely to grow like this:

Area content


Most of these chunks will be in the PHP program with if or for, and while to control their display state, although the template looks much more concise, but as long as a different display mode, PHP program is bound to change again!

In Smarty, everything is dominated by variables, and all rendering logic allows the template to control itself. Because Smarty will have its own template language, whether the block is to be displayed or repeated, it is presented with the Smarty template syntax (if, foreach, section) with variable content. It feels like a template gets a little complicated, but the advantage is that the PHP program does not have to change as long as it is properly planned.

From the above instructions, 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 codes in the PHP program. As long as you decide which of these variables to be in the template, let the template decide how to render the variables (even if they don't appear).

The foundation of Smarty

Installing Smarty

First, let's decide where the program should be placed.

There may be a location under Windows like this: "d:appservwebdemo".

Linux may have a location like this: "/home/jaceju/public_html/".

Download the latest Smarty kit from Smarty's official website: 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 copy the Libs directly to your program Master folder and rename it to class. That's it? That's right! This installation method is relatively simple, suitable for users who do not have their own 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, can be installed only once on the host, and then provided to all the designers under the host to develop different programs directly referenced, and not repeatedly installed too many Smarty copies. And the way I provide is suitable to bring the program to move over the program developers to use, so as not to worry about the host installed Smarty.

Folder settings for the program

With the author in Windows installation Appserv as an example, the program's Master folder is "d:appservwebdemo". After installing the smarty, we create the folder under the Master folder:

Under Linux, remember to change the permissions of Templates_c to 777. Windows will cancel it read-only.

The first small program written in Smarty

We first set the path of the Smarty, please name the following file as main.php, and put it under the Master 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 intention is to set the above way, if the program to transplant to other places, as long as the change __site_root can be. (This is the reference XOOPS)

Smarty The template path is set, the program will follow this path to catch the relative position of all the templates (in the example is @ #d:/appserv/web/demo/templates/@#). Then we use the display () This Smarty method to show our template.

Next we place a test.htm in the Templates folder: (The extension is nothing, but it is easy for visual designers to develop, the author is still based on. htm.) )

Templates/test.htm:



<title><{$title}></title>


<{$content}>






Now we're going to show the template above and replace the page title ($title) with the content ($content), name the following file test.php and place it under the Master folder:

test.php:

Require "main.php";
$tpl->assign ("title", "page title for Testing");
$tpl->assign ("content", "contents of test pages");
The above two lines can also be used instead of this line
$tpl->assign ("title" + "test page title", "Content" and "content" = "test page contents"));
$tpl->display (@ #test. htm@#);
?>




Please open the browser, enter http://localhost/demo/test.php try (according to your environment to determine the URL), you should see the following screen:



Next to Templates_c, we'll see a strange folder (%%179), and then click on it is also a strange folder (%%1798044067), which has a file:

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





<title><?php echo $this->_tpl_vars[@ #title @#];?></title>


_tpl_vars[@ #content @#];?>






Yes, this is the Smarty compiled file. It transforms our variables in the template into PHP syntax to execute, and the next time we read the same content, Smarty will crawl the file directly to execute it.

Finally, let's tidy up the whole Smarty program writing steps:

Step 1. Load the Smarty template engine.

Step 2. Establishes the 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 in the template using the Smarty assign method.

Step 5. Use the Smarty display method to show the Web page.

How to schedule 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 to imitate the architecture of XOOPS built out, because XOOPS is the author's contact with the program, a few use Smarty template Engine station program. The so-called watermelon on the big side, the author of this program architecture, although there is no XOOPS 1%, but at least for people to see when there are 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:


Include "class/smarty.class.php";
Define (@ #__SITE_ROOT @#, @ #d:/appserv/web/demo@#); No slash at the end.
Base on the position of the 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 that the program will not be lost everywhere, the overall architecture at a glance.

We also mentioned main.php, which is the main core of the entire program, whether it is a constant definition, external program loading, shared variable creation, etc., all started here. So after the module all just have to include this file in it. So during the process planning, it is necessary to think carefully about what should be put in the main.php, and it would be nice to use the include or require instructions to separate each link clearly.



In the previous section mentioned in the Smarty program 5 steps, main.php will help us first 3 steps to do a good job, the module behind the program as long as the next two steps to be done.

Start with the variable

How to use variables

From the example in the previous chapter, we can clearly see that we use the <{and}> to wrap the variables together. The default symbol is {and}, but for the Chinese code and JavaScript relations, so I still imitate XOOPS, will mark the symbol to replace. The name of the variable is exactly the same as the name of the PHP variable, and there is a $ font in front of it (this is different from the regular template engine). The sign is kind of like PHP.




(In fact, they are actually replaced with this), so the following template variants are possible:

1. <{$var}>

2. <{$var}>

3. <{$var

}>
In Smarty, the variable presets are whole-domain, meaning you only have to specify them once. If you specify more than two times, the contents of the variable will be the last specified. Even though we loaded the external sub-template in the main template, the same variables will be substituted in the sub-template, so that we do not have to do another parse action for the sub-template.

In the PHP program, we use Smarty's assign to put the variables into the template. The use of assign is already written in the official manual, as shown in the example in the previous section. However, when repeating chunks, we have to do some hands and feet on the variables before we can assign the variables into the template, which is mentioned in the next chapter.

Modify your variables

As we mentioned above, the Smarty variable presents a style that is determined by the template itself, so Smarty provides a number of functions for modifying variables. The following methods are used:

<{variable | modifier function}>

<{variable | modifier function: "parameter (not necessary, depending on function)"}>
Examples are as follows:

<{$var |nl2br}>

<{$var |string_format: "%02d"}>
Okay, so why let the template decide the style of the variable presentation itself? First look at the bottom of the HTML, this is a shopping cart checkout part of the picture.



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



Total amount: {format_total} dollar
In their PHP program, write this:


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




and Smarty template can be written like this: (Number_format modifier to the Smarty official website to download)



Total amount: <{$total |number_format: ""}> yuan
In Smarty PHP program, just write this:


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




So in Smarty we just have to specify the variable once, the rest to the template to decide on its own. Do you understand that? This is to let the template self-determination of the benefits of variable presentation style!

Content of the control template

Duplicate chunks

In the Smarty template, there are two ways to repeat a chunk: foreach and section. And in the program we are going to assign an array, which can contain array arrays. As in the following example:

Let's start by looking at how the PHP program is written:

test2.php:


Require "main.php";
$array 1 = Array (1 = "Apple", 2 = "Pineapple", 3 = "Banana", 4 = "Pattaya");
$tpl->assign ("Array1", $array 1);
$array 2 = Array (
Array ("index1" = "Data1-1", "index2" = "Data1-2", "Index3" and "Data1-3"),
Array ("index1" = "data2-1", "index2" = "data2-2", "Index3" and "data2-3"),
Array ("index1" = "data3-1", "index2" = "data3-2", "Index3" and "data3-3"),
Array ("index1" = "data4-1", "index2" = "data4-2", "Index3" and "data4-3"),
Array ("index1" = "data5-1", "index2" = "data5-2", "Index3" and "data5-3");
$tpl->assign ("Array2", $array 2);
$tpl->display ("test2.htm");
?>




And the template is written as follows:

Templates/test2.htm:




<title>Test duplicate chunks</title>


  
Using foreach to render array1
<{foreach item=item1 from= $array 1}>
<{$item 1}>
<{/foreach}>
Use section to present 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 present Array1
<{section name=sec2 loop= $array 2}>
INDEX1: <{$array 2[sec2].index1}>
Index2: <{$array 2[sec2].index2}>
INDEX3: <{$array 2[sec2].index3}>
<{/section}>







After performing the previous example, we found that either the foreach or section two execution results were the same. So what's the difference between the two?

The first difference is that foreach renders the two-layer array variables We assign in a nested way, and the section takes "the primary array [circular name]. Sub-array index" to render the entire array. As a Smarty, the foreach in the template is the same as the foreach in PHP, while the section is Smarty to deal with the narrative developed by the array variables listed above. Of course, the function of section is not only so, but in addition to the nested data presented in the next verse, the Official Handbook also provides several examples of the application of sections.

Note, however, that the array index that is dropped to the section must be a positive integer starting at 0, which is 0, 1, 2, 3, .... If your array index is not a positive integer starting with 0, you will have to use foreach to render your data. You can refer to this discussion in the official discussion area, which explores the use of section and foreach.

The presentation of nest-like data

The most vexing part of the template engine is probably the presentation of nested data, which many famous template engines will deliberately emphasize, but it's Smarty for the other.

The most common nest-like data, even on the forums program in the discussion of the subject area bar. Suppose you want to render the following results:

Announcement Area

Station Service Announcement

Literature Zone

Good Book Introduction

Chiven

Computer Zone

Hardware Peripherals

Software discussion

In the procedure 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" = "Station Service announcement")
)
),
Array ("category_id" = 2, "Category_name" and "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 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:



<title>Nested cycle Testing</title>














<{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 result of the execution is the same as the example I cited.

So, in the program, we just have to find a way to put the repeating value layer by piece into the array, and then use the <{first array [loop 1]. Second layer array [loop 2]. Third layer array [loop 3] ... The array index}> such a way to display the values in each nested loop. As for what method? We'll mention it when we use the database in the next section.

Transforming data in a database

The above mentioned how to show The nest loop, and in fact the application of our data may be fetched from the database, so we have to find a way to change the database data into the form of multiple arrays. Here I use a DB category to crawl the data in the database, you can use your favorite method.

We only modify the PHP program, template or the above (this is the advantage of the template engine ~), where $db this object is assumed to have been established in the main.php, and the data captured is the above example.

test3.php:


Require "main.php";
First layer array is created first
$category = Array ();
$db->setsql ($SQL 1, @ #CATEGORY @#);
if (! $db->query (@ #CATEGORY @#)) Die ($db->error ());
Capture data from the first layer of loops
while ($item _category = $db->fetchassoc (@ #CATEGORY @#))
{
Creating a second-level array
$topic = Array ();
$db->setsql (sprintf ($SQL 2, $item _category[@ #category_id @#]), @ #TOPIC @#);
if (! $db->query (@ #TOPIC @#)) Die ($db->error ());
Fetching data from the second layer of loops
while ($item _topic = $db->fetchassoc (@ #TOPIC @#))
{
Pushes the crawled data into the second-level array
Array_push ($topic, $item _topic);
}
Specifies a second-level array as a member of the data crawled by the first-level array
$item _category[@ #topic @#] = $topic;
Push the first layer of data into the first layer array
Array_push ($category, $item _category);
}
$TPL->assign ("forum", $category);
$tpl->display ("test3.htm");
?>




After fetching a piece of data from the database, we get an array containing the pen data. Through the while narrative and array_push function, we plug the data in the database into the array in a lump sum. If you only use a single-layer loop, remove the second loop (the red part).

Determines whether 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 is already logged in, our template can be written like this:

<{if $is _login = = true}>
Show User Action menu
<{else}>
Show forms for entering accounts and passwords
<{/if}>

Note that the "==" must be left at least one space on either side of the number, or Smarty will not be able to parse.

If the general application of the syntax can be referred to the official instructions, so the author here on the Unknown plus introduced. However, I found an interesting application: often see the program to produce such a table: (the number represents the order of the data set)

1 2

3 4

5 6

7 8

This author calls it "horizontal repeating table". Its characteristics and traditional longitudinal repetition are different, the previous sections we see the repeating table is from top to bottom, a column only a piece of information. The horizontal repeating table can produce n-data in a column horizontally, then replace one column until the end of the entire cycle. To achieve this, the simplest way to do this is to use the section and if collocation.

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@#);
?>




The template is written as follows:

Templates/test4.htm:



<title>Transverse repeating table test</title>












<{section name=sec1 loop= $my _array}> <{if $smarty. Section.sec1.rownum is div by 2}> <{/if}> <{/section}>
<{$my _array[sec1].value}>







The focus is on $smarty. Section.sec1.rownum this smarty variable, in the section loop, gets the index value starting at 1, so when rownum can be removed by 2, the outputChange the table to columns (note!) IsIn frontIn the back). So the number 2 is the number of data pens we want to present in a column. You can change other ways of presentation.

Loading External Content

We can load PHP program code or another sub-template in the template, respectively, using the include_php and include the two Smarty template syntax, include_php the author less use, the use of the way can be queried the official manual, here no longer described.

When using include, we can pre-load the sub-template, or dynamically load the sub-template. Pre-loading is commonly used in common file headers and copyright announcements, while dynamic loading can be used on a unified frames page, and further achieves a Winamp-like Skin-change. Of course, both of these can be mixed, 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 the variant in Template 2");
$tpl->assign ("Dyn_page", "test5_3.htm");
$tpl->display (@ #test5_1. htm@#);
?>




The template version 1 is written as follows:

Templates/test5_1.htm:




<title><{$title}></title>


<{include file= "test5_2.htm"}>

<{include file= $dyn _page}>
<{include file= "test5_4.htm" custom_var= "content of custom variable"}>






The template version 2 is written as follows:

Templates/test5_2.htm:

<{$content}>
The template version 3 is written as follows:

Templates/test5_3.htm:

This is the content of template 3
The template version 4 is written as follows:

Templates/test5_4.htm:

<{$custom _var}>
Here are a few points to note: 1. The location of the template is based on the previously defined template_dir; 2. All include in the sub-template, its variables will also be interpreted. ; 3. The include variable name = variable content can be used to specify the variables contained in the template included in the citation, as in the above template 4 practice.

http://www.bkjia.com/PHPjc/317633.html www.bkjia.com true http://www.bkjia.com/PHPjc/317633.html techarticle PHP designers, who are just beginning to touch the template engine, will find it hard to hear smarty. In fact, the author is no exception, touch all dare not touch a bit. But later in the anatomy of Xoops's program architecture, ...

  • 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.