PHP Smarty Basics

Source: Internet
Author: User
Tags html page html tags php language php code php template smarty template

Smarty is one of the most famous PHP template engines in the industry, using PHP as a template for PHP templates. It separates the logical code from the external content, provides an easy to manage and use method to separate the PHP code from the original HTML code. Simply speaking, the goal is to use the PHP programmer with the Art of separation, the use of programmers to change the logic of the program will not affect the design of the page, the art of modifying the page will not affect the program logic, which in many people cooperation project is particularly important.

What is a php template?

How do I get my PHP scripts to be independent from the design? This is undoubtedly one of the most asked questions on the PHP mailing list. Although PHP is advertised as an "HTML embedded language", after writing many PHP and HTML hybrid projects, I have an idea of separating the form from the content. Moreover, in many companies the role and program designers of planning designers are separate. As a result, such a template solution produces ...

For example, in a company, the development process for an application is as follows: After submitting the planning document, the interface designer [Art] produced a visual model of the site and handed it to the background programmer. Programmers use PHP to implement business logic, while using a façade model to make a basic architecture. Then the project is returned to the HTML page where the designer continues to refine. In this way, the project may come back and forth several times between the backend programmer and the page designer. Since background programmers don't like interfering with any HTML tags, they don't need to mix with the PHP code; the designer needs only the configuration files, dynamic blocks, and other parts of the interface that don't have to touch the intricacies of the PHP code. Therefore, it is important to have a good template support at this time.

Looking at many of today's PHP template solutions (such as Phplib), most of them simply provide a basic way to replace variables with templates and to format the features of dynamic blocks in a limited manner. But our needs are much higher than this. We don't want PHP programmers to design HTML pages at all, but that's inevitable. For example, if the artist wants to alternate a different background color between dynamic blocks, he may have to agree with the programmer beforehand. Similarly, artists should have their own configuration files for page design, which can also be dragged through variables into the template.

The birth of Smarty

As early as the late 1999, we started writing documentation for the template engine. After completing this document, we started writing a template engine with C and hopefully being included in PHP. While hitting a lot of technical problems, the question of "what the template should do and what not to do" is hotly discussed. From these experiences, we decided that we should use PHP to write the template engine as a class so that anyone who feels the right to use it. So we wrote an engine, and then there was smarty. (Note: This class has never been publicly published before). This class almost meets all of our requirements: conventional variable substitution, support including other templates, the use of profile integration settings, embedding PHP code, restricting the role of ' if ' statements, and more robust dynamic blocks that can be nested in multiple layers. It does this with regular expressions, and the code becomes rather confusing. The syntax and regular expressions are parsed every time the call is made, and it obviously slows down in a large application. In the programmer's eyes, the biggest problem is using PHP scripts to create and process all the necessary work for templates and dynamic blocks. How should we make him simpler?

We can imagine what the smarty should have done in the end. We know how fast PHP code will be without the cost of parsing the template, and we know how "scary" the PHP language is from a general graphic artist, but this can be masked by a simpler template syntax. How should we combine the strengths of these two approaches?

So, Smarty was born ...

Smarty Advantages

1. Speed: A program written with Smarty can achieve maximum speed, which is relative to other template engine technology.

2. Compile: The program written by Smarty to compile into a non-template technology php file, this file uses a mixed PHP and HTML, the next time the template to access the Web request directly to the file, And no more template recompilation (without changes to the source program)

3. Caching technology: A caching technique chosen by smarty, which caches the HTML files that the user eventually sees as a static HTML page, and when the cache property of the set Smarty is true, Converting a user's Web request directly into this static HTML file during the Cachetime period of the Smarty setting 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. If/elseif/else/endif can be used in templates. Using Judgment statements in template files makes it easy to rearrange templates.

A place not suitable for using smarty

1. Content that needs to be updated in real time. For example, like the stock display, it needs to update the data frequently, causing the template to be recompiled frequently, so this type of program uses Smarty to slow down the template processing speed.

2. Small projects. Small projects because the project is simple and art and programmer with a person's project, the use of smarty will be to some extent lost the advantages of PHP development quickly.

Smarty Concise Tutorial

I. Installation
First open the Web page http://smarty.php.net/download.php, download the latest version of the Smarty. Unzip the downloaded file (the directory structure is quite complex). Next, I will show you an example of installation, which should be extrapolate.
(1) A new directory learn/was established in the root directory, and a directory smarty/was established in learn/. The libs/copy of the directory that you just unzipped into the smarty/, and then in smarty/new Templates directory, templates in new cache/,templates/,templates_c/, config/.


(2) Create a new template file: Index.tpl, put this file in the Learn/smarty/templates/templates directory, the code is as follows:
Copy code<! DOCTYPE HTML Public "-//w3c//dtdhtml 4.01 transitional//en" " Http://www.w3.org/TR/html4/loose.dtd > new index.php, put this file under learn/:
Copy code<?php//references the class file require ' smarty/libs/smarty.class.php '; $smarty = new smarty;//Sets the path of each directory, this is the focus of the installation $smarty- >template_dir = "Smarty/templates/templates"; $smarty->compile_dir = "Smarty/templates/templates_c"; $smarty- >config_dir = "Smarty/templates/config"; $smarty->cache_dir = "Smarty/templates/cache";//smarty template has the function of caching, If this is true, open caching, but will cause the Web page does not immediately update the issue, of course, can also be resolved by other means $smarty->caching = false; $hello = "Hello world!"; /Assignment $smarty->assign ("Hello", $hello);//referencing template file $smarty->display (' Index.tpl ');? >

(3) The executive index.php will be able to see Hello world!.

Two. Assigning value

The values that need to be replaced in the template file are enclosed in braces {}, preceded by the $ number. For example, {$hello}. This can be an array, such as {$hello. item1},{$hello. item2} ...
The PHP source file only needs a simple function assign (var, value).
A 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

Three. Reference
Web pages in a Web site general headers and footer are common, so just refer to them in each TPL.
Example: *.tpl:
{include file= "HEADER.TPL"}

{* Body of template goes-here *}

{include file= "FOOTER.TPL"}

Four. Judge

In the template file, you can use the if else and other judgment statements, that is, you can put some logic programs in the template. "eq", "ne", "neq", "GT", "LT", "LTE", "Le", "GTE" "GE", "is even", "is odd", "are not even", "are notodd", "not", "mod", "Di V by "," Evenby "," Odd by "," = = ","!= "," > "," < "," <= "," >= "These are the comparisons that can be used in the IF. You can see what you mean.

Example:
{if $name eq "Fred"}

Welcomesir.

{elseif $name eq "Wilma"}

Welcomema ' AM.



Welcome,whatever you are.

{/if}
Five. Cycle

The method used to iterate through an array in Smarty is the section, how the assignment traversal is solved in the template, as long as a 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]}<br>
{/section}
OUTPUT:
Id:1000<br>id:1001<br>id:1002<br>

Six. Frequently Asked Questions
Smarty all braces {} as their own logic program, so we want to insert JavaScript functions in the Web page will need literal help, literal function is to ignore the curly braces {}.
Example: Copy code                < scriptlanguage=javascript>              function Isblank (field) {                         if (Field.value = = ")                                   {return false;}                          else                                  {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;                      Document.loginform.submit ();                                  return true;                                }              }         </script>{/literal}

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.