Home >Backend Development >PHP Tutorial >Detailed introduction to PHP template engine smarty_PHP tutorial
This article mainly introduces the detailed introduction of PHP template engine smarty. This article explains what smarty is, the advantages of smarty, and the places where smarty is not suitable. , smarty directory structure and version, friends in need can refer to it
/*
1. What is smarty?
Smarty is a template PHP template engine written in PHP. It provides the separation of logic and external content. Simply put,
The purpose is to use PHP programmers and artists to separate. The programmer changes the logical content of the program without affecting the page design of the artist. The artist re-modifies the page without affecting the program logic of the program. This is a problem in multi-person cooperation. is particularly important in projects.
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.
IV. 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 Smarty-stable-3.1.12, decompress it and 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 it can be accessed directly from the browser and is not safe. You can set the httpd.conf of apache , prohibit direct access to .tpl files, 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');
// PHP statement blocks cannot be executed in the calling template tpl file
$smarty->display('templates/index.tpl');
/*
index.tpl page content
Hello, {$name}
*/
/*
The processing process when Smarty is compiled 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
Smarty first compiles the PHP source file into an intermediate file (also PHP). If caching is enabled, a cache file (also PHP) is generated 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). One compile can be called multiple times (can be multiple times for a single file or multiple times for multiple files). If caching is enabled and there is a cache If the file has not expired, access the cache file directly and skip compiling the file.
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 template files or configuration files 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 to turn it off
$smarty->setcache_lifetime(60);//Set the cache time in seconds
//{*template file*}
//{nocache}
//{$name}
//{/nocache}
//{*If caching is turned on, the variables placed in the nocache tag will not be cached, and the value of the PHP source file is 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 the 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 files, all paths will be searched. The plugins folder contains storage files for functions that can be called in the foreground or background according to different rules. , the naming of file names and 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, do not set the default "templates"
$smarty->setTemplateDir("templates");
//Add the template directory path. All paths will be saved in array form. 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 variables
$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 pass {$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), scope The attribute marks the usage range of the template variable and 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]} You can also use {$testArr[] = 4} or other similar methods of creating arrays 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 it when creating or changing its value in the template. scope attribute and 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}
Templates containing templates 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 calling page inclusion
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 through the $sections attribute Specify the key and value under which tag to use
#$sections parameter can be omitted, 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 The key values in the configuration file can only be used in templates included after the current template introduces the configuration file statement, or in 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') to obtain the key value in the PHP source file. $smarty->getConfigVars('language') It may also be 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}
{*Operator can be ==,>=, etc. or it can be 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 the 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 in f2.tpl with the same name as f1.tpl, then f2.tpl will be fully imported and displayed with all the content in f1.tpl including the content of the block tag, and f2 All content in .tpl will be ignored
If f2.tpl has a block tag with the same name as 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, and will be displayed on the f2.tpl page , the content will still be displayed according to the format position set by f1.tpl. All other texts in f2.tpl, including unnamed block tags 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 Do not display
on this pageThis kind of inheritance supports multiple files and multiple inheritance, which means unlimited inheritance can be continued
*}
{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
?>