Home > Backend Development > PHP Tutorial > Detailed introduction to PHP template engine smarty, detailed introduction to template smarty_PHP tutorial

Detailed introduction to PHP template engine smarty, detailed introduction to template smarty_PHP tutorial

WBOY
Release: 2016-07-13 09:52:55
Original
738 people have browsed it

Detailed introduction to PHP template engine smarty, detailed introduction to template smarty

/*
1. What is smarty?

smarty is a template PHP template engine written in PHP. It provides the separation of logic and external content. To put it simply,
The purpose is to separate PHP programmers from artists. When programmers change the logic content of the program, it will not affect the page design of the artist. When the artist re-modifies the page, it will not affect the program logic of the program. This is particularly important in multi-person projects. appears to be particularly important.

2. Advantages of smarty:

1. Speed: Programs written using smarty can achieve maximum speed improvements, which is compared to other template engine technologies.

2. Compiled type: A program written in smarty must be compiled into a non-template technology PHP file at runtime. This file uses a mixture of PHP and HTML. The WEB request will be directly converted to this file the next time the template is accessed. file without recompiling the template (when the source program has not been changed)

3. Caching technology: A caching technology selected by smarty. It can cache the HTML file that the user finally sees into a static HTML page. When the cache attribute of smarty is set to true, the cache attribute set by smarty will During the cachetime period, the user's WEB request is directly converted into 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. If/elseif/else/endif can be used in templates. Using judgment statements in template files can very conveniently reformat the template.

3. Places where smarty is not suitable:

1. Content that needs to be updated in real time. For example, like stock display, which needs to update data frequently, using smarty for this type of program will slow down template processing.

2. Small projects. For small projects where the artist and programmer are both involved because the project is simple, using smarty will lose the advantage of rapid PHP development.


4. smarty directory structure and version
Open smarty’s official website, www.smarty.net/download.php. Download Smarty 3.1.12. There are tar.gz and zip for linux and windows versions respectively.

After downloading and decompressing Smarty-stable-3.1.12, you will get a Smarty-3.1.12 folder, which contains two main folders demo and libs

The demo folder is a sample folder, which contains the default folder structure and is the main folder where we will write program code. The names of the folders in the demo are all the default directory structure names of smarty. You can change the folder name to the name we want by changing the corresponding attribute value of smarty.
libs is the smarty code source folder and is generally not moved.

/libs/Smarty.class.php #Main file

/libs/sysplugins/ #Internal plugin

/libs /plugins/ #External plugin, can be freely expanded

/demo/cahce/ #Place cache files

/demo/configs / #Place configuration files that can be loaded

/demo/templates/ #Place template files

/demo/templates_c/ #Place the compiled template files

We can change the name of the unzipped Smarty-3.1.12 folder to the project name we want, and demo can also be changed to the name of the specific folder we want to store the encoding

2. Debugging 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. Commonly used ones are tpl, php, and html. It is not recommended to use the latter two because they can be accessed directly from the browser and are unsafe. You can set the httpd.conf of apache to prohibit direct access. Access the .tpl file or place the templates directory outside the website document tree)

*/

//index.php code
require('../libs/Smarty.class.php');
$smarty = new Smarty;
//In the called template, you can use {$name} to output the value of name, {} is the smarty delimiter here
$smarty->assign('name','zhang');
//The PHP statement block cannot be executed in the calling template tpl file
$smarty->display('templates/index.tpl');


/*
index.tpl page content


Hello, {$name}



*/

/*
The processing process during Smarty compilation is source PHP file -> template file (may be called multiple or multiple times) -> source PHP file. . .
In other words, it does not affect other processing and output of the original php file. So smarty template files can be complete html or part of it.

smarty processing process
Smarty first compiles the PHP source file into an intermediate file (also PHP). If caching is enabled, it then generates a cache file (also PHP) based on the compiled file. All parts that need to be cached are hard-coded.
Each subsequent access will access the compiled file (if the compiled file already exists), multiple calls are made for one compile (can be multiple times for a single file, or multiple times for multiple files), if caching is enabled and there is a cache file and there is no If it expires, the cache file will be accessed directly and the compiled file will be skipped.
Once the compiled file is generated, it will not be automatically updated unless the template file or configuration file is changed. Modification of the source PHP file will not trigger recompilation. Once the compiled files are regenerated, the cache files must also be regenerated.
*/

//Smarty allows two special compilation settings:
//1. No automatic recompilation at any time (online stage): It will only be generated if there is no compiled file for this file. Changes to the template file or configuration file will not trigger recompilation.
$smarty->setCompile_check(false);//The default is true, false means that the compiled file will not be generated at any time when the file changes, except that there is no compiled file.
$smarty->getCompile_check();//Get the current compilation check settings
//2. Recompile at any time (debugging phase): Recompile at any time.
$smarty->setForce_compile(true);//The default is false, true means recompiling every time (if caching is enabled, recaching every time)
$smarty->getForce_compile();//Get the current forced compilation settings

//Enable caching
$smarty->setCaching(true);
$smarty->getCaching();//Get the current cache status, the default is false
$smarty->setcache_lifetime(60);//Set the cache time in seconds
//{*template file*}
//{nocache}
//{$name}
//{/nocache}
//{*If caching is enabled, the variables placed in the nocache tag will not be cached, and the value of the PHP source file will be read each time*}


/*
smarty delimiter
In the template file, the distinction between ordinary html code and smarty code relies on delimiters. Default is {} but may conflict with js and css. Changes can be made.
In 3.0, template tags will not support spaces. For example, {$abc} can be recognized in Smarty2, but it will not work in 3.0. It must be like {$abc}. This is to better support javascript and css.
*/
$smarty->left_delimiter = "{"; //Left delimiter, 2.0 attribute, 3.0 follows
$smarty->right_delimiter = "}";
/*
The delimiter is equivalent to PHP's echo. The values ​​in the delimiter will be output unless operations such as assignment
The content between the two ** in the delimiter in the smarty tpl file is the comment content such as
tpl file:
{*This is the template comment content*}
*/


//Set the cache directory path, do not set the default "cache"
$smarty->setCacheDir("cache");
//Get cache directory path
$smarty->getCacheDir();

//Set the configuration directory path, no default "configs"
$smarty->setConfigDir("configs");
//Add the configuration directory path. All paths will be saved in array form. When calling the file, all paths will be searched
$smarty->addConfigDir("configs/test");
//Get the array of configuration directory paths
$smarty->getConfigDir();

//Set the plug-in directory path, no default "plugins"
$smarty->setPluginsDir("plugins");
//Add the plug-in directory path. All paths will be saved in array form. When calling the file, all paths will be searched. The plugins folder contains the storage files and file names of functions that can be called in the foreground or background according to different rules. And the naming of function names has different writing requirements according to different calling rules
$smarty->addPluginsDir("plugins/test");
//Get the array of plug-in directory paths
$smarty->getPluginsDir();

//Set the template directory path, no default "templates"
$smarty->setTemplateDir("templates");
//Add template directory path, all paths will be saved in array form, and when calling the file, all paths will be searched
$smarty->addTemplateDir("templates/test");
//Get the array of template directory paths
$smarty->getTemplateDir();

//Set the compilation directory path, do not set the default "templates_c"
$smarty->setCompileDir("templates_c");
//Get the compilation directory path
$smarty->getCompileDir();
/*
We can create different php source file folders and place the written php files in different folders according to certain categories.
Then 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 files, plug-ins, templates, and compilation directories of all php files in different folders to the same cache, configuration file, plug-in, template, and compilation directory
Let all PHP source files in this folder reference this configuration file to obtain the same configuration
*/


//Template variable
$arr = array(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. In the template to be called next, you can use {$testArr} or {$testArr['a'][0]} or {$testArr.a.0} to Access a specific array element
//In the template, you can directly change the value of the passed template variable through {$testArr = "testValue" scope="global"} (if it does not exist, create and set the template variable in the template), the scope attribute is annotation Template variable usage range does not need to be written
//Change or create other arrays in the template {$testArr = [1,2,3]} or {$testArr = [1,'a'=>2,2=>3]} or { $testArr[] = 4} or other similar create array methods in PHP
//The php source file can obtain the specified template variables through $smarty->getTemplateVars("testArr"). If you want to obtain the template variables changed or created in the template, you must add the scope attribute when creating or changing its value in the template. Set the value to scope="global" or scope="parent"

class A{
Function aa($nam){
echo $nam;
}
}
$smarty->assign("obj", new A);
//When the set template variable is an object, it can be called as follows on the template page. When passing a class object to the template, the address is also passed
//{$obj->aa('my name is y')}

//Smarty can recognize template variables embedded in double quotes, as long as the variable only contains numbers, letters, and underscores. But it seems that only template variables that can be directly converted into strings are supported
$smarty->assign("testStr", "this is testStr");
//The template can be accessed through {"$testStr OK !"}

/*
tpl template contains template
Template file:
{include file="header.tpl"}
header.tpl content:
This is the top content!! Welcome, {$name}

Template containing 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 variable passed when the calling page is included
header.tpl content:
{$testVar}, welcome, {$name}



*/

/*
A series of correspondences between variables and values ​​can be specified in advance, placed in the configuration file, and loaded when used.
The configuration file is placed in the configs folder by default, and the folder name can be customized.
*/

/*
#Template test.conf file:
The value corresponding to the # key can be enclosed in quotation marks
title = Welcome to Smarty!!
cutoff_size = 40

[china]
language = chinese

[england]
language = english

#[china], [england] are tags. The key value of the unset tag is global and can be used in the template as long as the configuration file is called. The key value of the set tag can only be specified when the configuration file is called. Only tags can be used
#Call the configuration file statement $smarty->configLoad('test.conf', $sections = 'england') in the PHP source file; only the template called under this statement can use the configuration file, and specify which one to use through the $sections attribute Key and value under tag
The #$sections parameter does not need to be written. The default value is null. $smarty->configLoad('test.conf') only uses the global key value and cannot use the key value under the label
#Call the configuration file through the {config_load file="test.conf" section="china" scope="global"} statement under the template
The #section attribute does not need to be written, the default is null, and the scope attribute must be written {config_load file="test.conf" scope="global"}
The #section attribute can be assigned three values ​​
#local Only the current template can use this configuration file
#parent Only the key values ​​in the configuration file can be used in the templates included after the current template introduces the configuration file statement, or in the templates called after the smarty object in the php source file calls the configuration file
#global The test effect is the same as parent
#Use the key value in the template through {#language#}, and you can also access the configuration file key value through {$smarty.config.language}
#You can use $smarty->getConfigVars('language') or $smarty->getConfigVariable('language') in the PHP source file to obtain the key value. It is also possible to obtain the key value with $smarty->getConfigVars('language') is an array
*/


/*
Commonly used 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}
{*Operators can be ==,>=, etc. or eq, ne, etc.*}

{for $x=0; $x {$x}
{/for}
{*for loop, similar to PHP code*}


{$x=0}
{while $x {$x }
{/while}
{*While loop, also similar to PHP code. *}



{foreach name="testForeach" from=$testArr key=arId item=arVal}
The corresponding value of {$arId} is: {$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-like formats*}
{foreach $testArr as $n}
{$n}
{/foreach}

{foreach $testArr as $key=>$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}
{*
The data in the literal tag area will be treated as web page HTML text. At this time, the template will ignore and not analyze all character information inside it.
This feature is used to display js and css that may contain character information such as braces. When these information are in {literal}{/literal} tags, the template engine will not analyze them and display them directly.
*}

*/

//PHP file:
//$smarty->setDebugging(true);//Debug templates for subsequent calls.
//$smarty->getDebugging();//Get whether debugging is currently performed, the default is false
//Or write {debug}

in the template that needs to be debugged

/*
Template file:

smarty3.0 supports template inheritance system, such as
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 there is no block tag in f2.tpl, or there is no block tag with the same name in f2.tpl as in f1.tpl, then f2.tpl will be fully imported to display all the content in f1.tpl including the content of the block tag, while f2.tpl All content will be ignored
If there is a block tag with the same name in f2.tpl as in f1.tpl, the content of the block tag in f2.tpl will overwrite the content of the block tag with the same name in f1.tpl when f2.tpl is displayed. When the f2.tpl page is displayed, the content It will still be displayed according to the format position set by f1.tpl. All other texts in f2.tpl including block tags without the same name and their contents will be ignored and not displayed.
The content of the block tag will only overwrite the content of the block tag with the same name in the parent template, or be displayed in the child template. If the parent template is not called on this page or there is no block tag with the same name to be overwritten in the parent template, the content of the block tag will be displayed on this page. Not shown in
This kind of inheritance supports multiple files and multiple inheritance, which means unlimited inheritance
*}


{fetch file="http://www.126.com" assign="testAssign"}
{$testAssign}
{fetch file="http://www.126.com"}
{*fetch can reference external http, ftp pages. If the value of assign is specified, the referenced content will be stored in the variable with the specified name. Otherwise, the fetch will be displayed wherever it is*}
*/

//php page:
//You can also use this method to call the template and do some processing before output
//$output = $smarty->fetch("index.tpl");
//do something with $output here to process the content to be output
//echo $output;//Then output the template

/*
Submit the form in the template


The action attribute can directly write the name of the PHP file to be submitted, or if you do not write empty action="", it will be submitted to the PHP file that calls the template
*/


//Connect to database
mysql_connect("localhost","root","root");
mysql_select_db("test");
$smarty->assign('webDir',$_SERVER['DOCUMENT_ROOT']);//$_SERVER['DOCUMENT_ROOT'] is the absolute path of the current project folder
//It is best to configure the src path of JQuery by writing an absolute path or a relative path that can find the JQuery in the file to be run because it needs to be compiled into a compiled file, and the compiled file is different from the original path environment
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1006115.htmlTechArticleDetailed introduction to PHP template engine smarty, detailed introduction to template smarty php /* 1. What is smarty smarty is a software that uses PHP The template is written out of PHP template engine, which provides logic and external content...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template