From IBM developerworks by Martin Streicher (martin.streicher@linux-mag.com ),
September 06, 2007
Mixing PHP with other web page tags at will make the program logic, HTML, Cascading Style Sheet (CSS), and JavaScript messy, making maintenance a daunting task. The smarty template engine can separate forms from functions.
Php web applications are easy to use. The PHP syntax is neat and easy to understand. PHP can be directly mixed with HTML, JavaScript, and CSS to quickly generate visual results. In addition, deploying PHP applications to your own web servers or hosting services is just a piece of cake.
However, it is also a responsibility to mix PHP with other page tags. PHP code is usually Structured Query Language (SQL) complex web (not joke) for queries, functions, classes, developer comments, HTML, CSS styles, and scripts ). What's worse, the content is stored in PHP,echo
There are many methods to send data to the output buffer. It is very laborious to maintain such messy pages. Making insignificant changes to code or tags can cause serious damage, and page enhancement may require the joint efforts of designers and programmers. Use PHP,Form(Page layout) andFunction(The purpose and structure of the page) will be mixed together.
Ideally, forms and functions are independent of each other. For example, CSS and HTML must be the same. CSS is a form, while HTML is a function. When using PHP, it is ideal if the page tag and code can be separated. The Code processes the input, makes a decision, and generates the displayed data, and the tag will expect the data to be obtained and provide the desired bracket for rendering information.
For example, the homepage tag may leave a "fill in the blank" (fill in the blank) for the user to log on, and other placeholders for saving the user's images and important information. ThisTemplate-- This is named because it provides the page display mode-only for designers, who control the overall appearance of the page and leave placeholders for names, images, and other data. The Code only provides data for placeholders. The tasks of developers are still focused on computing.
Of course, the form and function must work together. If the template expects an amount in USD, the Code should not provide a URL. If the template expects to obtain objects, the Code should not provide a list. Therefore, the template system must separate the form and function, but must also establish a connection between the two.
The most popular Web Application Programming Languages (Perl, Python, Ruby, and Java) all have template engines, and PHP is no exception. In the search engine, TypePHP template engine
, You may find more than 25 options (for a list that highlights each of the Engine Features under study, the PHP template engine Roundup, see references ).
Some PHP template engines have optimized the speed. Other PHP template engines are designed to encourage simplified use of separated forms and functions. In some packages, Placeholders are described in PHP, and other solutions have a customized short programming language. The selection of a template engine depends largely on the requirements, so it is suitable for a small amount of research and experimentation.
Here, I will introduce you to smarty, one of the most popular PHP template engines. The smarty "code" has its own syntax and operator extended list, but the system is not hard to learn. Read or browse the smarty document to familiarize yourself with all its functions. Starting with the small changes to smarty, you can expand your skills as needed and become more proficient.
Get smarty
The smarty web site maintains an active email list, a support forum, and an Internet Relay Chat (IRC) Forum (see references ). Development is in progress, and this article is based on v2.6.18, which was released on July 18, March 7, 2007.
Smarty has two aspects: PHP application programming interface (API) and Display Engine. The application code calls the API to associate the code variables with the template placeholder. The Display Engine interprets the smarty tag, execution loop, reference placeholder, and display final results. Smarty functions include:
-
Operator used to display all basic data structures of PHP
-
Display simple variables, iterate the entire array or associated array, and display class members.
-
Default Value of the placeholder
-
If PHP code does not associate variables with placeholders, the default value is displayed.
-
Control operators, such
if
,then
,else
Which content can be dynamically displayed based on input data
-
For example, the designer can use bold red text to show the negative account balance, and black text to show the positive balance. You can isolate the display logic in the template (so that you can develop it more easily ).
-
Loop Control, which provides special variables used to simplify building lists and tables
-
For example, you can test the first iteration of a loop and create a header. You can also execute the value round robin (round-robin) list in the same way as loop iteration. loop iteration is very suitable for changing the color of table rows.
-
Used to change data during renderingModifier
-
For example, you can use smarty to mark
<strong>{$name|upper}</strong>
Placeholder for uppercase and bold display-as shown in Figure
$name
.
<strong>
Is common HTML. Braces ({}
) Used to define the smarty tag,$name
Is a placeholder, while|upper
Is a modifier. You can also compile your own modifiers to extend the functions of smarty.
-
IfRequiredIncluding scripts and original PHP code.
literal
Andphp
Operator to complete
-
literal
All content in the operator is passed to the final page by word.
php
The Code placed in the operator will be embedded
<?php ... ?>
Execute the same operation as in the escape character.
You can also use{include ...}
Use an operator to reuse the smarty template. To improve performance, You Need To Cache each template to avoid the conversion load used each time. The smarty web site provides a wide range of documents and examples. Packt publishing also providesSmarty: PhP template programming and Applications(See references), which is suitable for learning and reference (warning: some of the latest operators are not introduced, and other operators are not correctly described, because this book introduces earlier versions of smarty v2.x ).
Development with smarty
You cannot use an article to list and demonstrate all functions of smarty. However, even a small example shown below can prove the strength of the template.
It is easy to add smarty to an application:
- Download the smarty.zip DEMO code (see download ).
- Decompress and install smarty in the path.
- Write an application that requires the use of the smarty class.
- Create two directories to place the application together:
- TemplatesThe template will be included
- Templates_cAdd the template containing the cache
For example, the folder content of the sample application containsExample.class.php index.php templates/ templates_c/
.
Files in the template directory will be read by the smarty engine. Make sure that the Web server has proper access to those files. In addition, the content of templates_c must be readable and writable, because cached template copies are placed in this folder. At least enable the Web server to write data to templates_c. Or, if you do not need to consider security issues, you can change the directory to the mode777
.
Listing 1 shows example. Class. php, a representative PHP V5 class. Listing 2 contains index. php, an application. Figure 1 shows the result of using a browser to access the sample application.
Listing 1. Simple PHP V5 class, used to store random lists of any type of named attributes
<?php
// // Example is a simple class that stores an arbitrary // number of named properties. //
class Example { private $catalog = array();
public function SetProperties( $arrayVariables ) { foreach ( $arrayVariables as $name => $value ) { $this->SetProperty( $name, $value ); } }
public function SetProperty( $name, $value ) { $this->$name = $value; $this->catalog[] = $name; }
public function GetProperties( ) { $result = array(); foreach ( $catalog as $name ) { $result[$name] = $this->GetProperty( $name ); }
return( $result ); }
public function GetProperty( $name ) { return ( $this->$name ); } } ?>
|
Example
Is a simple class used to persistently save any number of named attributes. The most interesting part of this class is the 18th rows$this->$name = $value;
. This line of code dynamically creates class instance members. For example, if you call$example->SetProperty( 'name', 'Groucho' )
, You can use (traditional)$example->name
Search name.
Listing 2. PHP applications without any web page tag
<?php require( 'Smarty.class.php' ); require( 'Example.class.php' );
$groucho = new Example(); $groucho->SetProperty( 'name', 'Groucho' ); $groucho->SetProperty( 'quote', 'Time flies like an arrow. Fruit flies like a banana.' );
$chico = new Example(); $chico->SetProperties( array( 'name' => 'Chico', 'quote' => "There's no such thing as a sanity clause!" ) );
$movies = new Example(); $movies->SetProperties( array( 'movies' => array( 'A Night at the Opera', 'Horse Feathers', 'Coconuts', 'The Big Store' )) );
$looks = new Example(); $looks->SetProperty( 'novelty', array( array( name =>'Groucho', 'signature' => 'moustache' ), array( name =>'Chico', 'signature' => 'hat' ), array( name => 'Harpo', 'signature' => 'raincoat' ), array( name => 'Zeppo', 'signature' => 'hair') ) );
$smarty = new Smarty(); $smarty->assign( 'person', $chico ); $smarty->assign( 'people', $looks->novelty ); $smarty->assign( 'quote', $groucho->quote ); $smarty->assign( 'movies', $movies->movies ); $smarty->display( 'template.tpl' ); ?>
|
Listing 2 shows a general strategy that associates PHP variables with the smarty placeholder. Code line$smarty->assign( 'name', $x )
PHP variables (or arrays and objects)$ XIs associated with a placeholder name. Displayed in TemplateNameAll locations are displayed.$ X.
Figure 1. render the final page, combined with forms and functions
What is the smarty template? The smarty code is lightweight, as shown in listing 3, listing 4, and listing 5. Smarty will put braces ({}
. Therefore, if any other page tag (such as embedded CSS or Javascript) uses braces{literal}...{/literal}
Enclose the tag, as shown in listing 3:
Listing 3. Simple header templates included in the main Template
<title>{$title|default:'The Marx Brothers'}</title> <style type="text/css"> {literal} body { font-family: Verdana, Arial, sans-serif; margin: 5%; } {/literal} </style> <body>
|
As described above, listing 3 will apply{literal}
Operator: All texts between delimiters are transmitted without further explanation. The name of row 3rd is displayed<title>
Is associated with the scalar variable in the PHP application. If it does not match<title>
Association, then|default:
The modifier provides the default value. Note the white space in the smarty operator. In general, you must ignore it. Fortunately, the smarty compiler will provide helpful error messages.
Listing 4 the footer shows the usage{if condition}
Make a decision during rendering. Here, if the placeholderquote
The value{if}
And{/if}
Between. Code line{$quote|upper}
Will be sent in uppercasequote
.|upper
It is one of the many modifiers used to change the string output-at the same time, it is very useful for separating the string Content and Display form.
Listing 4. footer Template
<div style="clear: both;"> <p align="center"> {if $quote} <{$style|default:'strong'}> {$quote|upper} </{$style|default:'strong'}> {/if} </p> </div> </body>
|
Listing 5 renders the final page.
Listing 5. Main smarty templates for Applications
{include file='header.tpl'}
<p> {$person->name} said, "{$person->quote}" </p>
<ul> {section name=index loop=$movies} <li> {$movies[index]} </li> {/section} </ul>
<table> {foreach item=person from=$people name=people} {if $smarty.foreach.people.first} <tr> <th>#</th> <th>Name</th> <th>Signature</th> </tr> {/if} <tr bgcolor="{cycle values="#eeeeee,#d0d0d0}"> <td>{$smarty.foreach.people.iteration}</td> <td>{$person.name}</td> <td>{$person.signature}</td> </tr> {foreachelse} <tr><td>Print this only if there's no data.</td></tr> {/foreach} </table>
{include file='footer.tpl'}
|
The main smarty template of the application uses several smarty operators:
-
{Include file ='Filename'}
-
Like PHP's own
include()
Run in the same way, insert and explain immediately at the appropriate location
filename
. Although not displayed, variables can be passed from one template to another, which encourages reuse.
-
{$ Person-> getproperty ('name ')}
-
Assume that
person
And
GetProperty()
. You can call object methods and reference object members, such
{$person->quote}
As you did.
-
{Section name =IndexLoop = $Placeholder}
-
Iteration in the array.
loop
The property name is given to the placeholder, and
name
Attribute specifies a name for the array index. In the loop, the array element is used
{$placeholder[index]}
.
-
Foreach
-
Image
section
The same iteration, but provides an excellent function to process a group of associated arrays, such as the row list queried by the database. Each associated array is "converted" to the name
item
. For example, in listing 5,
person
Named
item
. Every execution cycle,
person
Will be specified from the array
people
. After that, you can use keywords to reference values in the associated array during the entire loop process, as shown in
{$person.signature}
.
-
ForeachInNameAttribute
-
Similar to HTML tags
id
Attribute, which uniquely identifies a loop. Use this ID to reference a special variable set that reflects the cyclic state. For example, a special variable is
first
It is set only during the first iteration of the loop. Therefore, the value
$smarty.foreach.people.first
The
people
(
people
)
foreach
Loop (
foreach
) Associated special smarty variables (
smarty
). As you may think
last
Value and
iteration
Value, which starts from 1 and increases with each iteration (if you need a counter starting from scratch, use
index
Do not use
iteration
).
-
Cycle
-
Excellent operators used to build tables. If
values
List, Smarty will loop in all values like loop iterations. Add loop
bgcolor
The color of each table row can be changed to make the table clearer.
-
{Foreachelse}
-
If the array to be iterated is empty, it is displayed again
{foreachelse}...{/foreachelse}
.
Since you have previewed the template, listing 2 may be easy to read. As usual, listing 2 executes the computation and passes the rendering page to smarty. Code line$smarty->display('template.tpl')
Render the template. To capture the output of smarty, use$smarty->fetch('template.tpl')
.
Smarty is smarter than harder.
Although this example is designed, it shows the power and flexibility of smarty and how easy it is to use it to separate tags from code. Smarty has more tips. Smarty may implement almost all the functions you need. You can capture the template output to the smarty placeholder. You can filter templates, either before compilation or after compilation, or before rendering output is displayed or obtained. In addition, smarty allows you to cache templates.
Add to PHP code$smarty->caching = 1;
You can obtain the above features. If the cache is enableddisplay('template.tpl')
The template will be rendered as usual and a copy of the template will be saved in the cache. Next calldisplay('template.tpl')
The cached copy will be used instead of rendering the template.