Smarty is a php template engine. More precisely, it separates logic programs from external content and provides an easy-to-manage approach. You can describe different roles for both the application and the artist, because in most cases they cannot be the same person. For example, you are creating a Web page for browsing news, news headlines, tab bars, authors, and content that are content elements that do not include how they should be presented. In the Smarty program, these are ignored. Template designers edit templates, combining HTML tags and template tags to format the output of these features (HTML table, background color, font size, style sheet, and so on). One day programmers want to change the way the article is retrieved (that is, the change in program logic). This change does not affect the template designer, the content will still be accurately output to the template. In the same way, the artist eats too much and wants to completely redo the interface without affecting the program logic. As a result, programmers can change the logic without having to rebuild the template, and the template designer can change the template without affecting the logic.
Now let's briefly say what Smarty is not doing. Smarty does not attempt to separate the logic completely from the template. If the logic program is strictly used for page performance, then it will not have problems in the template. One suggestion: To keep the application logic away from the template, the page representation logic is far away from the application logic. This will make the content easier to manage later and the program can be upgraded more easily.
One of the features of Smarty is "template compilation". This means that Smarty read the template files and then use them to create PHP scripts. These scripts are created and will be executed later. Therefore, the parsing of template files is not spent, and each template can enjoy such as Zend Accelerator (http://www.zend.com) or PHP accelerator (http://www.php-accelerator.co.uk). Such a PHP compiler cache solution.
Some features of Smaty:
Very, very fast!
It's effective to do this chore with the PHP parser.
Do not need redundant template parsing, just compile once
Recompile only the modified template files
You can edit ' custom functions ' and custom ' variables ', so this template language can be fully extensible
You can set the template delimiter yourself, so you can use {}, {{}}, <!--{}-->
such as IF/ELSEIF/ELSE/ENDIF statements can be passed to the PHP parser, so {if ...} expressions are simple or complex, as you like.
If allowed, there can be unlimited nesting between sections
The engine can be customized. You can embed PHP code into your template file, although this may not be necessary (not recommended)
Built-in cache support
Standalone template file
Customizable Cache handling Functions
Plug-in architecture
1. Engine definition
PHP templates
How do i make PHP scripts stand out from the design? This is one of the most frequently asked questions on the PHP mailing list. Although PHP is advertised as an "HTML embedded language", the idea of separating forms and content has been created after many PHP and HTML-mixed projects have been written. Moreover, in many companies the role of the planning designer is separate from the programmer. So, a template solution like this produces ...
For example, in a company, the development process for an application is as follows: After submitting the plan document, the interface designer [artist] makes the appearance model of the website and then gives it to the background programmer. Programmers use PHP to implement business logic while using a façade model to create a basic architecture. Then the project is returned to the HTML page as the designer continues to refine. In this way, the project may go back and forth several times between the background programmer and the page designer. Because background programmers do not like to interfere with any of the HTML tags, but also do not need to mix the artists and PHP code, the designer only need to configure files, dynamic chunks and other interface parts, do not have to touch the intricacies of the PHP code. Therefore, it is important to have a good template support at this time.
Looking at the many PHP template solutions that exist today (such as Phplib), most of them simply provide a basic way to replace variables with templates and to format the dynamic chunks with limited functionality. But our needs are much higher than this. We don't want PHP programmers to design HTML pages at all, but this is inevitable. For example, if the artist wants to alternate background colors between dynamic chunks, he may have to speak with the programmer beforehand. Also, artists should have their own configuration files for page design, which can also be used to pull them into the template by using variables.
2. Key Benefits
1. Speed: The program written in Smarty can get the maximum speed improvement, which is relative to other template engine technology.
2. Compiled: The program written in Smarty is compiled into a non-template PHP file at runtime, this file is a mixture of PHP and HTML, the next time you access the template, the Web request directly into this file, Instead of recompiling the template (in case the source program has not changed)
3. Caching technology: Smarty chooses a caching technology that caches the HTML files the user eventually sees as a static HTML page, and when the cache property of the Smarty is set to True, The user's Web request is converted directly to this static HTML file during the Cachetime period set by Smarty, which is equivalent to calling a static HTML file.
4. Plug-in technology: Smarty can customize the plugin. Plugins are actually some of the custom functions.
5. If/elseif/else/endif can be used in the template. The template file can be easily reformatted by using a judgment statement.
Not suitable for use in smarty places
Content that needs to be updated in real time. For example, like a stock display, it needs to update the data frequently, and this type of program uses Smarty to slow down the processing of the template.
Small project. Small project because the project is simple and the artist and programmer are one-man project, the use of Smarty will lose some of the advantages of rapid development of PHP.
3. A Concise tutorial
One. Installation
Download the latest version of Smarty. Unzip the downloaded file (the directory structure is quite complex). Next, we will show you an installation example and see that it should be extrapolate.
(1) Create a new directory in the root directory learn/, and then create a directory smarty/in the learn/. The libs/copy of the directory just extracted to smarty/, and then in smarty/new Templates directory, templates 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:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" here DOCTYPE
Statement not all, the afternoon tangled up a good time, finally saw, novice friends concerned about the ">
<metahttp-equiv= "Content-type" content= "text/html;charset=gb2312" >
<title>Smarty</title>
<body>{# $hello #}
Create a new index.php and place this file under learn/:
<?php
Require ' smarty/libs/smarty.class.php ';
$smarty = new Smarty ();//Set the path of each directory, here 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 then open caching, but will cause the page not immediately update the problem, of course, can also be resolved by other means
$smarty->caching = false;
$smarty->left_delimiter = "{#";//redefine the boundary, because the default boundary "{}" character, the HTML page embedded in the JS script file to write code snippets using the "{}" character, the custom boundary character can also be <{}> } and so on
$smarty->right_delimiter = "#}";
$hello = "Hello world!"; /Assigned Value
$smarty->assign ("Hello", $hello);//reference template file
$smarty->display (' Index.tpl ');? >
(3) Execute index.php to see Hello world!.
Two. Assigning values
The value that needs to be replaced in the template file is enclosed in curly braces {}, and the value is preceded by a $ 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:
*.php:
$hello [name]= "Mr Green";
$hello [time]= "Morning";
$smarty->assign ("exp", $hello);
Output
hello,mr.green! Good morning
Three. References
Web pages in a Web site the header and footer are common, so you can refer to them in each TPL.
Example: *.tpl:
{include file= "HEADER.TPL"}
{* Body of template goes here *}
{include file= "FOOTER.TPL"}
4. Use Judgment
In a template file, you can use the If Else judgment statement, which allows you to put some logic programs in the template. "eq", "ne", "neq", "GT", "LT", "LTE", "Le", "GTE" "GE", "is even", "was odd", "is not even", "was notodd", "not", "mod", "Div b Y "," Evenby "," Odd by "," = = ","! = "," > "," < "," <= "," >= "These are the comparisons that can be used in the IF. Just look at it and you'll know what it means.
EQ equals,
NE, neq not Equal,
GT greater Than,
LT is less than
GTE, GE greater than equals,
LTE, le less than equals,
Not non, mod modulo.
Is (not) div by can be divisible by a number,
, B z m E m I W0 is (not) even is an even number,
$a is [not] even by $b i.e. ($a/$b)% 2 = = 0,
Is (not) odd is odd,
$a is not odd by $b ($a/$b)% 2! = 0
Example:
{if $name eq "Fred"}
Welcomesir.
{elseif $name eq "Wilma"}
Welcomema ' AM.
{Else}
Welcome,whatever is.
{/if}
5. Looping arrays
In Smarty, the method of iterating through an array is section, how the assignment traversal is resolved in the template, and the PHP source file can solve the problem with just one assign.
Example:
{*thisexamplewillprintoutallthevaluesofthe$custidarray*}
{sectionname=customerloop= $custid}
id:{$custid [Customer]}
{/section}
OUTPUT:
id:1000
id:1001
id:1002
6. Frequently Asked Questions
Smarty all of the curly braces {} are considered to be their own logic, so we want to insert JavaScript functions in the Web page need literal help, literal function is to ignore the curly braces {}.
Example:
{literal}
Functionisblank (field) {
if (field.value== ') {returnfalse;
}else{
Document.loginform.submit ();
Returntrue;
}
}
{/literal}
8. Interpretation procedures
We can see that the Smarty program part is actually a set of code that conforms to the PHP language specification, which we'll explain in turn:
1:/**/statement:
The included section is the program header comment. The main content should be the role of the program, copyright and author and writing time to do a simple introduction, which is not required in smarty, but from the procedural style, this is a good style.
2:include_once statement:
It will install the Smarty file to the Web site into the current file, note that the included path must be written correctly.
3: $smarty =newsmarty ():
This sentence creates a new Smarty object $smarty, a simple instantiation of an object.
4: $smarty->templates (""):
This sentence indicates the path of the $smarty object when using the TPL template, it is a directory, in the absence of this sentence, smarty the default template path is the templates directory of the current directory, the actual writing process, we will write this sentence, this is a good program style.
5: $smarty->templates_c (""):
This sentence indicates the directory at which the $smarty object was compiled. In the template design we already know that Smarty is a compiled template language, and this directory is the directory where it compiles templates, note that if the site is located on a Linux server, make sure
The directory defined in Teamplates_c has a writable and readable permission, and by default its compilation directory is the Templates_c of the current directory, and for the same reason we write it explicitly.
6: $smarty->left_delimiter and $smarty->right_delimiter:
Indicates the left and right delimiters when a template variable is found. "{" and "}" by default, but in practice because we want to use it in the template
For "{#" and "#}" or "" "or other glyphs, note that if the left and right delimiters are defined here, in the template file corresponding to each variable with the same definition of the same symbol, for example, here is specified as" <{"and"}> ", the HTM template also
The corresponding {$name} becomes <{$name}>, so that the program can correctly find the template variable.
7: $smarty->cache ("./cache"):
Tells the location of the Smarty output template file cache. The previous article we know Smarty the biggest advantage is that it can be cached, this is the directory to set the cache. By default, the cache directory under the current directory, equivalent to the Templates_c directory, is in the Linux system
We want to make sure it's readable and writable.
8: $smarty->cache_lifetime=60*60*24:
This will be the time in seconds to calculate the cache validity. When the first cache time expires, the cache is rebuilt when the caching variable of Smarty is set to true. When its value is-1, it means that the established cache never expires, and 0 indicates that each time the program executes
The deposit is always re-established. The above setting indicates that the Cache_lifetime is set to one day.
9: $smarty->caching=1:
This property tells Smarty whether to cache and how to cache. It can take 3 values, 0:smarty the default value, means that the template is not cached, 1: Indicates that Smarty will use the currently defined cache_lifetime to decide whether to end Cache;2: represents
Smarty will use the value Cache_lifetime when the cache is built. It is customary to use true and false to indicate whether to cache.
: $smarty->assign ("name", "Zaocha"):
The prototype for this number is assign (Stringvarname,mixedvar), varname is the template variable used in the template, var indicates the variable name to replace the template variable, its second prototype is assign (Mixedvar), We want to explain in detail in the following example the use of this member function, assign is one of the core functions of smarty, all the substitution of the template variable to use it.
One. $smarty->display ("Index.tpl"):
The function is displayed as display (Stringvarname), which acts as a template. Simply put, it will parse the processed template display, where the template file does not add the path, as long as the use of a file name, it is the path we have already defined in $smarty->templates (Stringpath).
After the execution of the program we can open the current directory of the Templates_c and the cache directory, we will find a few more than a few percent of the directory, these directories are smarty compilation and cache directory, it is automatically generated by the program, do not directly modify these generated files.
Introduce some common basic elements in the Smarty program, and in the example below you can see that they will be used more than once.
Smarty Tutorial 1. Engine definition 2. Key Benefits 3. Simple Tutorial 4. Use Judgment 5. Loop Array 6. FAQ 8. Interpreter