PHP template engine smarty-PHP Tutorial

Source: Internet
Author: User
Tags php template
PHP template engine smarty. PHP template engine smarty detailed introduction this article mainly introduces the PHP template engine smarty detailed introduction, this article explains what is smarty and smarty advantages, what is not suitable for using smarty, and detailed introduction to the smar PHP template engine smarty.

This article mainly introduces the PHP template engine smarty in detail. This article describes the advantages of smarty and smarty, the places that are not suitable for using smarty, and the smarty directory structure and version, for more information, see

  

/*

1. what is smarty?

Smarty is a PHP template engine written in PHP. it separates the logic from external content,

The purpose is to separate PHP programmers from the artist. the programmer used to change the logic content of the program does not affect the webpage design of the artist. the engineer re-modifies the page and does not affect the program logic, this is particularly important in projects with multiple partners.

II. Advantages of 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.

3. areas not suitable for using smarty:

1. content to be updated in real time. For example, for a stock display, it needs to update data frequently. Using 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 have one project at the same time, using smarty will lose the advantage of rapid php development.

IV. smarty directory structure and version

Open the official smarty website www.smarty.net/download.php. Download Smarty 3.1.12. Tar.gz and zip are applicable to linux and windows respectively.

After downloading the Smarty-stable-3.1.12 file, decompress it to get a folder named Smarty-3.1.12, which contains two main folders: demo and libs.

The demo folder contains the default folder structure, which is the main folder for programming code. The folder name in the demo is the default directory structure name of smarty. you can change the folder name to the desired name by changing the property value of smarty.

Libs is the smarty code source folder, which generally does not move.

/Libs/Smarty. class. php # main file

/Libs/sysplugins/# internal plugin

/Libs/plugins/# external plugin, which can be expanded freely

/Demo/cahce/# Place cached files

/Demo/configs/# place the configuration file that can be loaded

/Demo/templates/# place the template file

/Demo/templates_c/# place the files compiled for the template

You can change the name of the extracted Smarty-3.1.12 folder to the project name we want, and change the demo to the name of the folder where the encoding is stored.

2. debug Smarty-3.1.12

Create your own file and create index. php in the demo folder.

Create Template index. tpl in the templates Directory

(It can be the extension of almost any text file, which is commonly used in tpl, php, and html. We do not recommend the latter two because they can be accessed directly from a browser, which is not safe. You can set httpd. conf of apache to prohibit direct access to the. tpl file. Or place the templats directory outside the website document tree .)

*/

// Index. php code

Require ('../libs/Smarty. class. php ');

$ Smarty = new Smarty;

// In the called template, {$ name} can be used to output the name value zhang, and {} is the smarty separator here.

$ Smarty-> assign ('name', 'zhang ');

// The PHP statement block cannot be executed in the template tpl file.

$ Smarty-> display ('Templates/index. tpl ');

/*

Index. tpl page content

  

  

Hello, {$ name}

  

  

*/

/*

The process for Smarty compilation is the source PHP file> template file (which may be called multiple or multiple times)> Source PHP file...

That is to say, it does not affect other processing and output of the original php file. Therefore, the smarty template file can be a complete html file or a part of it.

Smarty processing

Smarty first compiles the php source file into an intermediate file (also php). If cache is enabled and then a cache file (also php) is generated based on the compiled file, all the files to be cached are hard-coded.

Each subsequent access will access the compiled file (if the compiled file already exists) and call it multiple times at a time (it can be a single file multiple times or multiple times ), if cache is enabled and cached files are not expired, you can directly access the cached files and skip compiling files.

Once the compilation file is generated, it will not be automatically updated unless the template file or configuration file is changed. Modifying the source PHP file will not cause re-compilation. Once the compiled file is re-generated, the cached file must be re-generated.

*/

// Smarty allows two special compilation settings:

// 1. do not re-compile automatically at any time (in the launch phase): This file is generated only when there is no compilation file for this file. changes to the template file or configuration file will not cause re-compilation.

$ Smarty-> setCompile_check (false); // The default value is true. false indicates that no compilation file is generated when the file is changed.

$ Smarty-> getCompile_check (); // get the current compilation check settings

// 2. re-compile at any time (debugging phase): re-compile at any time.

$ Smarty-> setForce_compile (true); // The default value is false. true indicates re-compilation every time (cache is enabled, and cache is re-cached every time)

$ Smarty-> getForce_compile (); // gets the settings for the current forced compilation

// Enable cache

$ Smarty-> setCaching (true );

$ Smarty-> getCaching (); // gets the current cache status. the default value is false.

$ Smarty-> setcache_lifetime (60); // sets the cache time in seconds.

// {* Template File *}

// {Nocache}

// {$ Name}

// {/Nocache}

// {* If cache is enabled, the variables placed in the nocache tag will not be cached. The value of the PHP source file is read each time *}

/*

Smarty delimiter

In a template file, distinguishing between common html code and smarty code relies on delimiters. The default value is {}, but it may conflict with js and css. Can be changed.

In 3.0, the template tag does not support spaces. for example, {$ abc} can be identified in Smarty2, but it cannot be identified in 3.0. it must be like {$ abc }, this is to better support javascript and css.

*/

$ Smarty-> left_delimiter = "{"; // left delimiter, attribute 2.0, followed by 3.0

$ Smarty-> right_delimiter = "}";

/*

The delimiters are equivalent to PHP echo, and all values in the delimiters are output, unless assigned values or other operations

The content between the two ** operators in the smarty tpl file is the comment content, as shown in figure

Tpl file:

{* This is the template comment *}

*/

// Set the cache directory path. the default "cache" is not set"

$ Smarty-> setCacheDir ("cache ");

// Obtain the cache directory path

$ Smarty-> getCacheDir ();

// Set the configuration directory path. the default "configs" is not set"

$ Smarty-> setConfigDir ("configs ");

// Add the configuration directory path. all paths will be saved as arrays. when you call a file, you will find

$ Smarty-> addConfigDir ("configs/test ");

// Obtain the array of the configured directory path

$ Smarty-> getConfigDir ();

// Set the directory path of the plug-in. the default "plugins" is not set"

$ Smarty-> setPluginsDir ("plugins ");

// Add the directory path of the plug-in. all paths will be saved as arrays, and files will be searched in all paths when being called, the plug-ins folder contains the storage files of functions that can be called in the foreground or background according to different rules. The names of file names and function names have different writing requirements according to different calling rules.

$ Smarty-> addPluginsDir ("plugins/test ");

// Obtain the array of the directory path of the plug-in

$ Smarty-> getPluginsDir ();

// Set the template directory path. the default "templates" is not set"

$ Smarty-> setTemplateDir ("templates ");

// Add the directory path of the template. all paths are saved as arrays. when you call a file, you can find

$ Smarty-> addTemplateDir ("templates/test ");

// Obtain an array of template directory paths

$ Smarty-> getTemplateDir ();

// Set the compiling directory path. the default "templates_c" is not set"

$ Smarty-> setCompileDir ("templates_c ");

// Obtain the compiling directory path

$ Smarty-> getCompileDir ();

/*

We can create different php source file folders and classify the php files into different folders.

Create a custom config file in each folder and create a new $ smarty = new Smarty object in the config file.

Then, set the cache, configuration file, plug-in, template, and compiling directory of PHP files in different folders to the same cache, configuration file, plug-in, template, and compiling directory.

Make all PHP source files in this folder reference this configuration file to get the same configuration

*/

// Template variable

$ Arr = array ("zhang", "li"), 'a' => array ("liu", "wang"), array ("ming ", "yi "));

$ Smarty-> assign ("testArr", $ arr );

// Set Template variables to provide variables for the template to be called, you can use {$ testArr}, {$ testArr ['A'] [0]}, or {$ testArr. a.0} to access a specific array element

// In the template, you can directly use {$ testArr = "testValue" scope = "global"} to change the value of the passed template variable (if it does not exist, create and set it in the template ). the template variable ), scope attributes indicate the scope of use of template variables.

// Modify or create another array in the template {$ testArr = [1, 2]} or {$ testArr = [1, 'A' => 2, 2 => 3]} or {$ testArr [] = 4} or another method similar to creating an array in PHP

// For the php source file, you can use $ smarty-> getTemplateVars ("testArr") to obtain the specified template variables. for example, you need to obtain the Template variables changed or created in the template, when creating or changing a value in a template, you must add the scope attribute and set the value to scope = "global" or scope = "parent"

Class {

Function aa ($ nam ){

Echo $ nam;

}

}

$ Smarty-> assign ("obj", new );

// When the set template variable is an object, it can be called on the template page as follows. when the class object is passed to the template, it is also an address.

// {$ Obj-> aa ('My name is Y ')}

// Smarty can identify the template variable embedded in double quotation marks, as long as this variable only contains numbers, letters, and underscores. However, it seems that only Template variables that can be directly converted into strings are supported.

$ Smarty-> assign ("testStr", "this is testStr ");

// You can use {"$ testStr OK! "} To access

/*

Tpl template includes Template

Template File:

{Include file = "header. tpl "}

Header. tpl content:

This is the top content !!, Welcome, {$ name}

The template can also be in this format.

{Include file = "header. tpl" testVar = "this is the top content !!! "}

Header. tpl can use {$ testVar} to use the template variables that are included in the call page.

Header. tpl content:

{$ TestVar}, welcome, {$ name}

*/

/*

You can specify the correspondence between a series of variables and values in advance and put them in the configuration file for loading during use.

The configuration file is stored in the configs folder by default. you can customize the folder name.

*/

/*

# Template test. conf file:

# Values corresponding to keys can be enclosed in quotation marks.

Title = Welcome to Smarty !!

Cutoff_size = 40

[China]

Language = chinese

[England]

Language = english

# [China] and [england] are tags. if the key value of the tag is not set to global, you only need to call this configuration file and use it in the template, the key value of the tag can be used only when the corresponding tag is specified when the configuration file is called.

# Call the configuration file statement $ smarty-> configLoad ('test. conf ', $ sections = 'England'); the template called under this statement can use this configuration file. the key and value under which tag to use are specified through the $ sections attribute.

# $ Sections parameter can be left blank. the default value is null. $ smarty-> configLoad ('test. Conf') only uses global key values, but not key values under tags.

# Use the {config_load file = "test. conf" section = "china" scope = "global"} statement in the template to call the configuration file

# The section attribute can be left empty. the default value is null. the scope attribute must be set to {config_load file = "test. conf" scope = "global "}

# Section attributes can be assigned with three values

# Local only the current template can use this configuration file

# Parent only contains the template after the current template introduces the configuration file statement, or the keyvalue in the configuration file can be used in the template called after the smarty object in the php source file calls the configuration file

# The global test results are the same as those of parent.

# Use the key value {# language #} in the template, or use {$ smarty. config. language} to access the key value of the configuration file.

# In the PHP source file, you can use $ smarty-> getConfigVars ('language') or $ smarty-> getConfigVariable ('language') to obtain the key value, $ smarty-> getConfigVars ('language ') returns an array.

*/

/*

Common functions in tpl files

Tpl file:

  

  

{Capture name = "testCapture "}

{Include file = "f1.tpl "}

{/Capture}

{If true}

{$ Smarty. capture. testCapture}

{/If}

{If $ name = "wang "}

Welcome wang.

{Elseif $ name = "zhang "}

Welcome zhang.

{Else}

Welcome, whatever you are.

{/If}

{* Operator can be ==,>=or eq or ne *}

{For $ x = 0; $ x

{$ X}

{/}

{* For loop, similar to PHP code *}

{$ X = 0}

{While $ x

{$ X ++}

{/While}

{* While loop, similar to PHP code. *}

  

{Foreach name = "testForeach" from = $ testArr key = arId item = arVal}

{$ ArId} corresponds to {$ arVal}

  

{$ Smarty. foreach. testForeach. index}

{$ Smarty. foreach. testForeach. iteration}

{$ Smarty. foreach. testForeach. first}

{$ Smarty. foreach. testForeach. last}

{$ Smarty. foreach. testForeach. total}

  

{Foreachelse}

$ TestArr is null

{/Foreach}

{* You can also use the following two PHP formats *}

{Foreach $ testArr as $ n}

{$ N}

{/Foreach}

{Foreach $ testArr as $ key =>n n}

{$ Key}

{/Foreach}

{$ SectionArr = [0 => "a", 4 => "B", "c", "d", "e", 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 16]}

{Section name = "testSection" loop = $ sectionArr start = 0 step = 4 max = 6 show = true}

{$ Smarty. section. testSection. index }-

{$ SectionArr [testSection]}-

{$ Smarty. section. testSection. iteration }-

  

{Sectionelse}

$ SectionArr is null

{/Section}

  

  

  

*/

/*

Tpl template file:

{Literal}

  

{/Literal}

{*

Data in the literal label area is processed as html text of a webpage. in this case, the template ignores and does not analyze all characters in the template.

This feature is used to display js and css that may contain characters such as braces. When the information is in the {literal} {/literal} tag, the template engine directly displays the information without analyzing them.

*}

*/

// Php file:

// $ Smarty-> setDebugging (true); // debug the template that will be called later.

// $ Smarty-> getDebugging (); // You can check whether debugging is performed. the default value is false.

// Or write {debug} to the template to be debugged}

/*

Template File:

Smarty3.0 supports the template inheritance system, such

F1.tpl:

  

  

{Block name = 'top'} f1.header
{/Block}

{Block name = 'middle'} f1.middle
{/Block}

{Block name = 'buttom '} f1.buttom
{/Block}

  

  

F2.tpl:

{Extends file = "f1.tpl "}

{Block name = 'top'} f2.header
{/Block}

{Block name = 'other'} it can't be show
{/Block}

{*

If f2.tpl does not contain block tags, or f2.tpl does not contain block tags with the same name as f1.tpl, f2.tpl completely introduces all content in f1.tpl including block tags, all content in f2.tpl will be ignored.

If f2.tpl contains a block tag with the same name as f1.tpl, the block tag content in f2.tpl will overwrite the block tag content in f1.tpl, the content will still be displayed in the format set by f1.tpl. All other texts of f2.tpl, including block tags without the same name, and their content, will be ignored and not displayed.

The content of the block tag only overwrites the content of the block tag with the same name in the parent template, or is displayed in the subtemplate, if no block tag of the same name is called in the parent template or the parent template, the block tag content is not displayed on this page.

This inheritance supports multi-file and multi-inheritance, meaning that it can be inherited infinitely.

*}

{Fetch file = "http://www.126.com" assign = "testAssign "}

{$ TestAssign}

{Fetch file = "http://www.126.com "}

{* Fetch can reference external http and ftp pages. if The assign value is specified, the referenced content will be included in the variable with the specified name. otherwise, where can fetch be displayed *}

*/

// Php page:

// You can also use this method to call the template and perform some processing before the output.

// $ Output = $ smarty-> fetch ("index. tpl ");

// Do something with $ output here to process the content to be output

// Echo $ output; // then output the template

/*

Form submitted in template

The action attribute can be directly written into the php file name to be submitted, or submitted to the php file that calls the template without empty action = "".

*/

// Connect to the database

Mysql_connect ("localhost", "root", "root ");

Mysql_select_db ("test ");

$ Smarty-> assign ('webdir', $ _ SERVER ['document _ root']); // $ _ SERVER ['document _ root'] indicates the absolute path of the current project folder.

// Configure the src path of JQuery. it is best to write the absolute path or write the file to be run to find the relative path of JQuery. because the file to be compiled is different from the original path

?>

  

Ghost This article mainly introduces the PHP template engine smarty in detail, this article explains what is the advantages of smarty, smarty is not suitable for the use of smarty, smar...

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.