PHP Template engine Smarty

Source: Internet
Author: User
Tags php template delete cache smarty template

First, The characteristics of Smarty

Speed: Faster compared to other template engines

compiled: Direct access to the compilation file the next time the template is accessed, no more template recompilation

Caching Technology: you can cache HTML files that the user eventually sees as a static HTML

plug-in technology:smarty can customize plug-ins, plugins are actually some of the custom functions

Powerful performance logic: if/else if/end If/foreach can be used in templates

Second, The basic use of smarty ( 1 ) index.php The page is entered as follows

<?php

1. Introduction of the Smarty class

Include ' smarty/libs/smarty.class.php ';

2. Instantiating Smarty Objects

$smarty = new Smarty ();

3. Setting related properties

$smarty->template_dir = "Templates"; Template Catalog

$smarty->compile_dir = "Templates_c"; Compiling the Directory

modifying delimiters

$smarty->left_delimiter = ' <{';

$smarty->right_delimiter = '}> ';

4. Assigning data

$smarty->assign ("title", "Smarty template Engine");

$smarty->assign ("content", "Hello World" of the Smarty template engine);

5. Load View

$smarty->display (' index.html ');

( 2 ) on the view page index.html Enter the following

<! DOCTYPE html>

<meta charset= "UTF-8" >

<title>{$title}</title>

<body>

{$title}

<p>{$content}</p>

</body>

Second, The basic grammar of Smarty ( 1 ) delimiter

Smarty The default delimiter in the { }

① any content outside the delimiter is static and will not be parsed (including PHP code)

② delimiter begins with "{" Symbol and variable $ cannot have spaces before, for example {$title} will not be parsed

The CSS or JS {} in the ③ page will also be considered as delimiters, conflict, and handled as follows:

A) You can add spaces at the beginning of the {

b) CSS and JS are added in a way that is externally introduced

c) Use the built-in function {literal} {required parsing css or JS} {/literal}

④ Modify the delimiter, enter the following code in the PHP page of the Smarty configuration:

$smarty->left_delimiter = ' <{';

$smarty->right_delimiter = '}> ';

( 2 ) Note

Write Smarty comments in the Index.html view page using the <* Comment content *>

( 3 ) Variable

The main variables in Smarty are the following three types:

① through the Assign function in the PHP program

② Reserved variables

③ Configuration variables

①assign variables

PHP in the 8 type of data:

422 Lineup

4: Four scalar types, integer, floating-point, String, Boolean

2: Two composite types; arrays, objects

2: Two special types, resources and NULL

Distribution Assign variables:

$user =array ("Tom", "Jim", "Jack");

$smarty->assign (' user ', $user);

In the View page, enter {$user [0]}, or point syntax {$user. 0} to get the appropriate place for Tom

Reserved Variables

No need to allocate in PHP, directly can be used in the template page variables. Includes super global variables in PHP, such as: $_get,$_server, and some of the variables that are included with Smarty

Use format: {$smarty. Reserved variable name}

Example: {$smarty. Server.server_name}

  Configuration Variables

It is not required to be assigned in a PHP program, but differs from the reserved variable, which is configured through the configuration file

Here's an example: Create a Profile config.conf, enter the following, and the configuration file must be created in a folder named Configs folder

copyright= "Copyright Information"//profile double quotes can be removed

Police= Filing Information

[Nationnality]

name=nationnality

[TIME]

name=time

PHP page call Smarty engine

<?php

1. Introduction of the Smarty class

Include ' smarty/libs/smarty.class.php ';

2. Instantiating Smarty Objects

$smarty = new Smarty ();

3. Setting related properties

$smarty->template_dir = "Templates";

$smarty->compile_dir = "Templates_c";

$smarty->display (' config.html ');

To invoke configuration information:

You can invoke configuration information by entering the following in the View page

{config_load file= "test.conf" section= "Time"}//referencing the configuration file and noting the use of the time section

Because there are two name in the configuration file, the load file is indicated as the time part, so the time is output here

( 4 ) function ( Smarty the middle function is divided into three main categories) built-in functions

1. {if} {ElseIf} {else}

Each {if} must have a paired close tag: {/if}

Built-in function Use example: Enter the following in the View page

{if $iq >= 130}

Tom

{ElseIf $iq <130 && $iq >=110}

Jack

{ElseIf $iq <110 && $iq >=90}

Lucy

{Else}

Jim

{/if}//Paired close tag

2. {foreach}

An example of using a Foreach loop to output a two-dimensional array is as follows:

{foreach} the main properties are as follows 6 A:

A) @index, current array index, calculated starting from 0

b) @iteration, the current number of cycles, calculated starting from 1

c) @first, this value is true for the first cycle

d) @last, the value is true when looping to the last time

e) @total, the total number of cycles, which can be used inside the foreach or after the loop is complete

f) @show, after the Foreach Loop executes, detects whether the loop shows the data

examples of how to use this are: @first For example, give the first TR Add class name

3. {section}

When using the section loop, note that the section cannot be used for associative arrays, only for successive subscript arrays (0,1,2, ...). ), use loops for associative arrays, need to use {foreach}

The relevant parameters are as follows:

Example of how to use: Enter the following in the View page

{sectionname= "item" Start=0} indicates that the loop starts from item No. 0

<li>{$user [item]}</li>//$user Here is an indexed array

{/section}

Use Index , First properties such as:

Use Section you can traverse multiple arrays in a single loop:

  Variable Decorators

In general, in the template page, directly output the variables allocated in the PHP program can be, but there are some special cases, you need to assign the variable/reserved variable, re-processing, Smarty provides a variable decorator

Examples of use are:

{$smarty. Now|date_format:"%y-%m-%d%T"}//using the Smarty time decorator

{$content|truncate:10}//modifier with limit character length

{"Hello"|str_repeat:10}//Repeat Output hello10 times

......

  function plugins (custom functions)

(1) Html_radios

{html_radiosname= "names" values= $value output= $outlabs selected= "2"}

Calling this code in the view page is equivalent to creating a corresponding <input type= "Radio" > Hints message

The output here is the external hint of input

Selected=2 indicates that the 2nd value is selected

(2) Html_checkbox// how to use and Html_radios basically the same

{html_checkboxname= "names" values= $value output= $outlabs selected= "Tom"}

If you want to set the default to select multiple options, set the value of selected as an array

(3) html_options (drop- down list )

{html_optionsname= "names" options= $array selected=3}

No setting under Select, option assigns an associative array, value is the key of the array

(4) Cycle ( alternating loop value )

View Page Example://Output Interlaced class

<tr class= "{cyclevalues= ' One,two,three '}" >

<td>{$v .id}</td>

<td>{$v .name}</td>

<td>{$v .age}</td>

</tr>

iii. references to Smarty in the project ( 1 ) introduced Smarty

Placed in the framework means that Smarty is part of the framework

placed in the application, is a third-party way to introduce Smarty, (Third_party)

( 2 ) configuration Smarty

Here is an example of a third-party introduction:

in the application>controllers>home>indexcontroler.class,php file

Publicfunction indexaction () {

Introducing the Smarty Class

Includeapp_path. " Third_party/smarty/smarty.class.php "

Instantiating a Smarty Object

$smarty = new Smarty ();

Setting related properties

Template_dir = Cur_view_path $smarty. "Templates";

Compile_dir = Cur_view_path $smarty. "Templates_c";

assigning data

$smarty-Assign (' Cats ', $cats);

$smarty-Assign (' Bestgoods ', $bestGoods);

Loading template files

$smarty, display (' index.html ');

}

( 3 ) configuration Smarty Optimized ( BaseController.class.php )

The code in the above (2) can be written to the underlying control class, and the other controllers inherit from the underlying control price, allowing for reuse

( 4 ) template contains

You can extract the header HTML page, and then refer to the include built-in function method to inject the proposed head.html page into another page, {includefile = "head.html"}

iv. cache of Smarty ( 1 ) The underlying use of the cache

The main caching methods are: Data cache and File cache

Smarty cache belongs to the file cache: generate static pages

Smarty set the cache:

Turn on caching

$smarty->caching=true;

Set the cache directory (the folder where the response needs to be created)

$smarty->cache_dir=cur_view_path. " Cache

Set Cache validity period

$this->smarty->cache_lifetime=60; (Default validity is 3600, in seconds)

Turn on Smarty call mode

$smarty->debugging=true; (You can turn on the Debug page)

The current page is the homepage

$smarty->assign (' index ', true);

Smarty provides a method of judging whether to cache: iscached

Examples of use are:

if (! $smarty->iscached (' index.html ')) {// indicates no cache

Execute code

}

( 2 ) Local does not cache

cache Control for tags ( NoCache properties)

Display time: {$smarty. Now|date_format: '%y-%m-%d%t '} has cache refresh time unchanged

Display time: {$smarty. Now|date_format: '%y-%m-%d%t ' nocache} Remove Cache

cache control for variables (for a single variable, the third parameter is set to true )

Declaring variables: $time =date ("y-m-d h:i:s");

$smarty->assign ("time1", $time);

$smarty->assign ("time1", $time,true); Declares that the third argument is true, that the variable is not cached

cache control for template areas ( {nocache} {/nocache} suitable for a piece of area)

Use the {NoCache} built-in function on the view page to remove the cache, as shown in the following example:

{NoCache}

{/nocache}

( 3 ) Single-template multi-cache (multiple cache files generated on the same page)

You only need to enter a differentiated parameter when loading the template file (parameters passed in the URL)

$smarty->display (' goods.html ', $goods _id);

It is also necessary to enter this parameter when judging the cache:

$smarty->iscached (' goods.html ', $goods _id)

( 4 ) Cache Group

Set up a cache group:

$smarty->display ("list.html", "$size | $brand | $style | $material")

( 5 ) Delete Cache

Cache failure Condition: expired, template page changed, cache file deleted

Delete Home Cache

$smarty->clearcache ("index.html");

Delete page Specify parameter cache

$smarty->clearcache ("goods.html", 2);

Delete all Caches

$smarty->clearallcache ();

The underlying method used to delete a file is the unlink () function

PHP Template engine Smarty

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.