Php smarty template entry instance

Source: Internet
Author: User
Tags create index html page html tags php code php template tag name root directory smarty template

PHP Smarty template-what is Smarty?
Smarty is a PHP template engine written using PHP. It is one of the most famous PHP template engines in the industry. It points

 
Smarty of php

Apart from logical code and external content, it provides an easy-to-manage and use method to separate PHP code logic that is originally mixed with HTML code. Simply put, the purpose is to use PHP programmers to separate themselves from the artist. The programmer used to change the logic content of the program does not affect the artist's page design, and the artist re-modifies the page does not affect the program logic, this is particularly important in projects with multiple partners.

 

PHP Smarty template-what is a PHP template?
How can I separate my PHP scripts from the design? This is undoubtedly one of the most asked questions on the PHP mail list. Although PHP is advertised as an "HTML embedded language", after writing many PHP and HTML hybrid projects, I came up with the idea of separating forms and content. In addition, in many companies, the roles of planning designers are separated from those of program designers. Therefore, such a template solution ......

For example, in a company, the development process of an application is as follows: after submitting the plan document, the interface designer [artist] creates the website appearance model and then submits it to the background programmer. Programmers use PHP to implement business logic, while using appearance models to make the basic architecture. Then the project is returned to the HTML page and the designer continues to improve. In this way, the project may return several times between the background programmer and the page designer. Background programmers do not like to interfere with any HTML tags and do not need to mix the programmers and PHP code. The artist only needs to configure files, dynamic blocks, and other interface parts, you don't have to deal with complicated PHP code. Therefore, it is very important to have a good template support.

Looking at many existing PHP template solutions (such as PHPLIB), most of them only provide the basic methods to replace variables with templates and format dynamic blocks with limited functions. However, our demand is much higher than this. We do not want PHP programmers to design HTML pages at all, but this is inevitable. For example, if an artist wants to alternate different background colors between dynamic blocks, he may have to negotiate with the programmer in advance. Likewise, artists should have their own configuration files for page design, which can also be pulled to the template through variables.

 

PHP Smarty template-the birth of Smarty
As early as the late 1999 S, we began to write instructions for the template engine. After completing this document, we started to use C to write a template engine and hopefully it will be included in PHP. While encountering many technical difficulties, the question "What is a template and what should be done?" was also discussed enthusiastically. From these experiences, we decided to use PHP to write the template engine into a class so that anyone who feels appropriate can use it. So we wrote an engine, and we now have Smarty. (Note: This class has never been publicly published before ). This class almost meets all our requirements: regular variable replacement, supporting other templates, using configuration file integration settings, Embedding PHP code, limiting the role of the 'if' statement, there are more robust dynamic blocks that can be nested in multiple layers. It does this with regular expressions, and the code becomes quite confusing. During each call, we had to parse those syntaxes and regular expressions. So in large applications, it obviously slowed down. From the programmer's perspective, the biggest problem is to use PHP scripts to create and process all the necessary work for templates and dynamic blocks. How should we make it easier?

We can imagine what the Smarty should do. We know how fast PHP code will be without the template parsing overhead, and we also know from the perspective of general artists how terrible PHP is ", however, this can be concealed by a simpler template syntax. How should we combine the strengths of these two methods?

So, Smarty was born ......

 

Advantages of PHP Smarty template-Smarty
1. Speed: programs written with Smarty can achieve the maximum speed improvement, which is relative to other template engine technologies.

2. compilation type: a program written in Smarty must be compiled into a non-template PHP file during runtime. This file adopts a mix of PHP and HTML, during the next Template access, the WEB request is directly converted to this file, instead of re-compiling the template (without modifying the source program)

3. cache technology: a cache technology used by Smarty to cache the HTML file that the user sees as a static HTML page. When the cache attribute of Smarty is set to true, during the cachetime period set by Smarty, user WEB requests are directly converted to this static HTML file, which is equivalent to calling a static HTML file.

4. Plug-in technology: Smarty can customize plug-ins. Plug-ins are actually some custom functions.

5. You can use if/elseif/else/endif in the template. Using judgment statements in the template file can easily rearrange the template format.

Not suitable for Smarty

1. Content to be updated in real time. For example, for a stock display, it often needs to update the data, resulting in frequent re-compilation of the template, so the use of Smarty for this type of program slows down the processing speed of the template.

2. Small projects. Small projects because the project is simple and the artist and programmer are both one-person projects, using Smarty will lose the advantage of rapid PHP development to a certain extent.

 

PHP Smarty template-brief tutorial on Smarty
1. Installation
First open the webpage. net/download. php "> http://smarty.php.net/download.php to download the latest smarty. Decompress the downloaded file (the directory structure is quite complex ). Next we will show you how to install an instance.
(1) create a new directory named learn/under the root directory, and create a directory named smarty/In learn /. Copy the libs/from the extracted directory to smarty/, create the templates directory in smarty/, and create cache/, templates/, templates_c/, config/in templates /.


(2) create a new template file: index. tpl. Place the file in the learn/smarty/templates Directory. The code is as follows:
[Code]

 

 


Smarty
{$ Hello}

[/Code]
Create index. php and put this file under learn:
[Code]
Template_dir = "smarty/templates ";
$ Smarty-> compile_dir = "smarty/templates/templates_c ";
$ Smarty-> config_dir = "smarty/templates/config ";
$ Smarty-> cache_dir = "smarty/templates/cache ";

// The smarty template has the high-speed cache function. If this parameter is set to true, the caching is enabled, but the webpage will not be updated immediately. Of course, you can use other methods to solve this problem.
$ Smarty-> caching = false;

$ Hello = "Hello World! "; // Assign a value
$ Smarty-> assign ("hello", $ hello); // reference the template file
$ Smarty-> display ('index. tpl ');?>
[/Code]

(3) execute index. php to see Hello World! .

II. Assignment

The values to be replaced in the template file are enclosed in braces {}, and $ is added before the value. For example, {$ hello }. This can be an array, for example, {$ hello. item1}, {$ hello. item2 }...
In the PHP source file, only a simple function assign (var, value) is required ).
Simple example:
*. Tpl:
Hello, {$ exp. name }! Good {$ exp. time}

*. Php:
$ Hello [name] = "Mr. Green ";

$ Hello [time] = "morning ";
$ Smarty-> assign ("exp", $ hello );
Output:
Hello, Mr. Green! Good morning

III. References
Generally, the headers and footer of webpages can be shared, so you only need to reference them in each tpl.
Example: *. tpl:
{Include file = "header. tpl "}

{* Body of template goes here *}

{Include file = "footer. tpl "}

IV. Judgment

In the template file, you can use judgment statements such as if else to place some logic programs in the template. "Eq", "ne", "neq", "gt", "lt", "lte", "le", "gte" "ge", "is even ", "is odd", "is not even", "is notodd", "not", "mod", "div by", "evenby", "odd ", "= ","! = ","> "," = "Are the comparisons that can be used in if. Let's see what it means.

Example:
{If $ name eq "Fred "}

WelcomeSir.

{Elseif $ name eq "Wilma "}

WelcomeMa 'Am.


       
Welcome, whatever you are.

{/If}
V. Loop

In Smarty, the method of traversing arrays cyclically is section. How to assign values to traversal is solved in the template, and only one assign in the php source file can solve the problem.
Example:
{* This examplewill print out all the values of the $ custid array *}

{Sectionname = customer loop = $ custid}

Id: {$ custid [customer]}
{/Section}
OUTPUT:
Id: 1000id: 1001id: 1002

6. FAQs
Smarty regards everything in braces {} as its own logic program, so we need literal help to insert javascript functions on the webpage, the literal function is to ignore braces {}.
Example: [code]

        
        

Function isblank (field ){

If (field. value = '')
{Return false ;}

Else
                                {

Document. loginform. submit ();
Return true;

                                }

              }

{/Literal} [/code]

Here is a simple smarty instance.

The smarty template is said to be recommended by php.net. It is said that it has strong functions and is said to be fast.

It is said that more and more people are using

The official website smarty.php.net contains forums, downloads, and manuals. If you have everything you want, go to the topic:
(-) Installation:
After the downloaded package is decompressed, there are three sub-directories: The template file directory is a directory of four class files under <libs>. first, we will introduce the most important: Smarty. class. php should be the core class of the whole smarty template. It is also used to deal with it in normal times. The following directory structure is created under your application directory:
/App_1/smarty/libs
/App_1/smarty/templates_c
/App_1/smarty/templates
/App_1/smarty/configs

<Libs> put the class files required by smarty under the libs Directory of the corresponding compressed package
<Templates> Store template files. All template files used by the program are stored here.
<Configs> stores the module attribute file, which will be detailed later.
<Templates_c> store the "compiled" template file. Later, we will detail that some directories need to be set to 777.
<Cache> save the cached template file

The above file name is the default file name of smarty. You can specify different file names, such as guest_template_dir and admin_template_dir. If not specified, the above file name will be used.
(2) usage:

Design template:
1 Template variable: {$ variable name}, for example, {$ color}, {$ type}
Test_color.tpl
<Font color = {$ color}> {$ name} </font>
Test_url.tpl
<A href = "{$ url}" target = "{$ target}" >{$ title} </a>

2. You can also use a template array.
Test_array.tpl
{People. name} <br>
{People. sex} <br>
{People. money} <br>
3. List of blocks used by the template
For example:
User1 user‑sex user‑money
User2 user2_sex user2_money
User3 user3_sex user3_money

Section. tpl
You can format the table:
<TABLE>
{Section name = user loop = $ userList}
<TR>
<TD >{$ userList [user]. name} </TD>
<TD >{$ userList [user]. sex} </TD>
<TD >{$ userList [user]. money} </TD>
</TR>
{/Section}
</TABLE>


<? Php
// Under app_1 of the current directory
// Generate $ smarty instance

Require ('smarty/lib/smarty. class. Php ');
$ Smarty = new Smarty;

// Specify the function directory, which can be customized
$ Smarty-> template_dir = 'smarty/templates ';
$ Smarty-> $ compile_dir = 'smarty/template_c ';

// Assign a value to the template variable Template: color. tpl is stored in smarty/templates.
// $ Smarty-> assign ('Template variable name', 'php internal variable ');
// $ Smarty-> display (template file name );

$ Smarty-> assign ('color', 'red ');
$ Smarty-> assign ('name', 'Hello World ');

// Display template
// Output: <font color = red> helloworld </font>
$ Smarty-> display ('test _ color. tpl ');

// Assign values to the template array variable. Template: test_array.tpl
// Output:

// Ba dou
// Male
// A litte
$ People = array ('name' => 'badou ', 'sex' => 'male', 'Money' => 'A little ');
$ Smarty-> assign ('people', $ people );
$ Smarty-> display ('test _ color. tpl ');

// Template block
// {Section name = user loop = $ userList}
// Section: Label function
// Name: Tag name
// Loop: loop array
// Function cyclically outputs multiple rows
// Output:

// User1 userpolicsex user=money
// User2 user2_sex user2_money
// User3 user3_sex user3_money


$ UserList [] = array ('name' => 'user1', 'sex' => 'user1 _ sex', 'Money' => 'user1 _ money ');
$ UserList [] = array ('name' => 'user2', 'sex' => 'user2 _ sex', 'Money' => 'user2 _ money ');
$ UserList [] = array ('name' => 'user3', 'sex' => 'user3 _ sex', 'Money' => 'user3 _ money ');

$ Smarty-> assign ('userlist', $ userList );
$ Smarty-> display ('test _ section. tpl ');
?>
Writing this item is the most basic thing for the time being, and the code is not tested. I am not responsible for any errors in my first writing.
There are also a lot of interesting functions that you will have the opportunity to write

 

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.