PHP smarty Template engine

Source: Internet
Author: User
Tags php template smarty template

<?PHP/*First, what is Smarty?smarty is a php template used to write a template engine, it provides a separation of logic and external content, in brief, the purpose is to use a PHP programmer with the art separation, the use of programmers to change the logic of the program content does not affect the design of the art page, The artist re-modifying the page does not affect program logic, which is especially important in a multi-person collaborative project. Second, Smarty advantages: 1. Speed: The program written in Smarty can get the maximum speed improvement, which is relative to other template engine technology. 2. Compiled: The program written in Smarty is compiled into a non-template PHP file at runtime, this file is a mixture of PHP and HTML, the next time you access the template, the Web request directly into this file, Instead of recompiling the template (in case the source program has not changed) 3. Caching technology: Smarty chooses a caching technology that caches the HTML files the user eventually sees as a static HTML page, and when the cache property of the Smarty is set to True, The user's Web request is converted directly to this static HTML file during the Cachetime period set by Smarty, which is equivalent to calling a static HTML file. 4. Plug-in technology: Smarty can customize the plugin. Plugins are actually some of the custom functions. 5. If/elseif/else/endif can be used in the template. The template file can be easily reformatted by using a judgment statement. Third, not suitable for the use of Smarty Place: 1. Content that needs to be updated in real time. For example, like a stock display, it needs to update the data frequently, and this type of program uses Smarty to slow down the processing of the template. 2. Small project. Small project because the project is simple and the artist and programmer are in one person's project, using Smarty will lose the advantage of rapid development of PHP. 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 respectively for Linux and Windows versions. Download good after smarty-stable-3.1.12 extract will get a Smarty-3.1.12 folder, there are two main folders demo and Libsdemo folder as a sample folder, which contains the default folder structure, is the main folder in which we want to write program code. The name of the folder in the demo is smarty the default directory structure name, you can change the smarty corresponding attribute value, and then change the folder name to the name we want. Libs is a Smarty Code source folder and is generally not moving. /libs/smarty.class.php #主文件/libs/sysplugins/#内部plugin/libs/plugins/#外部plugin, can freely expand/demo/cahce/#放置缓存文件/demo/configs /#放置可以载入的配置文件/demo/templates/#放置模板文件/demo/templates_c/#放置对模板编译后的文件可以把解压得到的 Smarty-3.1.12 folder name changed to the name of the project we want, demo can also Change to the name of the folder that we want to store the encoding in. 2, debug Smarty-3.1.12 Create your own files, and create index.php under the Demo folder. Creating template Index.tpl in the Templates directory (which can be almost any text file extension, commonly used tpl,php,html, is not recommended, since it can be accessed directly from the browser and is not secure.) Apache httpd.conf can be set to prohibit direct access to the. tpl file. or place the Templats directory outside the site document tree. )*///index.php Coderequire(‘.. /libs/smarty.class.php ');$smarty=NewSmarty;//in the called template, you can output the value of name by {$name} zhang,{} is the Smarty delimiter here$smarty->assign (' name ', ' Zhang ');//The PHP statement block cannot be executed in the call template TPL file$smarty->display (' Templates/index.tpl ');/*index.tpl page Content *//*Smarty Compile-time processing is the source PHP file, template file (may call multiple or more than one), source PHP file ... This means that the original PHP file is not affected by other processing and output. So the Smarty template file can be either full HTML or part of it. Smarty processing process smarty PHP source files, first compiled into intermediate files (also PHP), if the cache is enabled, and then according to the compilation file generated cache files (also PHP), the part that needs to be cached is all hard-coded. Each subsequent visit accesses the compiled file (if it already exists), compiles multiple calls at a time (which can be multiple times of a single file, or multiple files), and if caching is enabled and the cache file is not expired, the cache file is accessed directly and the compiled file is skipped. Once the compiled file is generated, it will not be automatically updated unless the template file or configuration file changes. The source PHP file modification does not cause recompilation. Once the compilation file is regenerated, the cache file will inevitably regenerate. *///Smarty allows for the existence of two special compilation settings://1, not automatically recompiled at any time (on-line): Only if no compiled file for the file is generated, the template file or configuration file changes, and no recompilation is thrown. $smarty->setcompile_check (false);//The default is True,false, which means that no compile files are generated at any time, except in the case of file changes. $smarty->getcompile_check ();//get the settings for the current build check//2, recompile at any time (Debug phase): Recompile at any time. $smarty->setforce_compile (true);//The default is False,true, which means recompiling every time (caching is enabled every time)$smarty->getforce_compile ();//get settings for the current forced compilation//Turn on caching$smarty->setcaching (true);$smarty->getcaching ();//gets the current cache state, the default is false off$smarty->setcache_lifetime (60);//set cache time Unit seconds//{* template file *}//{nocache}//{$name}//{/nocache}//{* If the cache is turned on, the variables placed in the NoCache tag will not be cached, each time the PHP source file value is read *}/*Smarty The delimiter in the template file, the distinction between ordinary HTML code and Smarty code is by the delimiter. The default is {}, but may conflict with JS and CSS. Changes can be made. In 3.0 the template label will not support spaces, such as {$ABC} can be recognized in Smarty2, but 3.0 is not, it must be {$ABC}, so as to be able to better support JavaScript and CSS. */$smarty->left_delimiter = "{";//left delimiter, 2.0 attribute, 3.0 inherited$smarty->right_delimiter = "}";/*The delimiter is the same as the echo of PHP, the value in the delimiter will be output, unless the assignment is smarty the content of two * * in the delimiter in the TPL file is a comment content such as a TPL file: {* This is the template comment content *}*///set the cache directory path without the default "cache"$smarty->setcachedir ("Cache");//Get Cache directory path$smarty-Getcachedir ();//set the configuration directory path with no default "Configs"$smarty->setconfigdir ("Configs");//Add a configuration directory path, all paths will be saved as an array, and will be found in all paths when the file is called$smarty->addconfigdir ("Configs/test");//gets an array of configuration directory paths$smarty-Getconfigdir ();//set the plug-in directory path with no default "plugins"$smarty->setpluginsdir ("Plugins");//add plug-in directory path, all paths will be saved as an array, the call file will be found in all paths, the plugins folder is a function can be called in the foreground or background by different rules of the stored files, filenames and function names according to different calling rules have different requirements for writing$smarty->addpluginsdir ("Plugins/test");//gets an array of plug-in directory Paths$smarty-Getpluginsdir ();//set the template directory path with no default "templates"$smarty->settemplatedir ("Templates");//add a template directory path, all paths will be saved as an array, and will be found in all paths when the file is called$smarty->addtemplatedir ("Templates/test");//gets an array of template directory paths$smarty-Gettemplatedir ();//set the Compile directory path with no default "Templates_c"$smarty->setcompiledir ("Templates_c");//get the compiled directory path$smarty-Getcompiledir ();/*we can build different PHP source files folder, put the PHP files written in a certain category in different folders. Then create a custom config file in each folder, create a new $smarty in the config file, and then put all the different folders of the PHP file cache, config file, plugin, template, compile directory are set to the same cache, Config file, plugin, template, compile directory so that all PHP source files under this folder can refer to the configuration file to get the same configuration*///Template Variables$arr=Array(Array("Zhang", "Li"), ' a ' + =Array("Liu", "Wang"),Array("Ming", "Yi"));$smarty->assign ("Testarr",$arr);//set the template variable to provide a variable for the template that will be called, which can be accessed through {$TESTARR} or {$testArr [' a '][0]} or {$testArr. a.0} in the template that is called next. 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 Scope property is the label template variable usage range can not be written//changed in template or created into another array {$ Testarr = [+]} can also {$testArr = [1, ' A ' =>2,2=>3]} can also be {$TESTARR [] = 4} or other similar to the creation of arrays in PHP//php source files can be $smarty- Gettemplatevars ("Testarr") gets the specified template variable, such as to get the stencil variable that is changed or created in the templates, you must add the scope property when creating or changing its value in the template, and set the value to Scope= "global" or scope= "parent "classa{functionAa$nam){        Echo $nam; }}$smarty->assign ("obj",NewA);//when you set the template variable to be an object, the template page can be called as follows, and the template-passing object is also addressed//{$obj->aa (' My name is y ')}//smarty can identify template variables embedded in double quotes as long as the variable contains only numbers, letters, and underscores. But it seems to support only template variables that can be converted directly to strings.$smarty->assign ("Teststr", "This is Teststr");//The template can be passed {"$testStr OK!"} To access/*The TPL template contains template template files: {include file= "HEADER.TPL"}HEADER.TPL content:<span> This is the top content!!, welcome, {$name}</span> The template contains a template that can also be the format {include file= "HEADER.TPL" testvar= "This is the top content!!!"} HEADER.TPL can be used to include the template variable Header.tpl content from {$testVar} using the calling page: <span>{$testVar}, welcome, {$name}</SPAN><HR/ >*//*A series of variables and values can be pre-defined and placed in the configuration file and loaded when used. The configuration file is placed in the Configs folder by default and can be customized to modify the folder name. *//*#模板test. conf file: #键对应的值可以不用引号括起来title = Welcome to smarty!! Cutoff_size = 40[china]language = Chinese[england]language = English#[china],[england] is a label, The key value of the label is not set globally as long as the configuration file is called to be used in the template, set the label's key value only when the configuration file is called to specify the corresponding label can use # in the PHP source file call Profile statement $smarty->configload (' test.conf ', $sections = ' England '); The template that is called below the statement can use the configuration file, using the $sections property to specify the key and value under which label to use # $sections parameter can be not written, the default value is NULL, $smarty- Configload (' test.conf ') uses only the global key value, not the key value under the tag # under the template through {config_load file= "test.conf" section= "China" scope= "global"} Statement Call Profile #section property can not be written, default is Null,scope property must write {config_load file= "test.conf" scope= "global"} #section属性可赋三种值 #local Only the current template can use the profile #parent only the template that is included in the current template's introduction of the profile statement, or the template that is called after the Smarty object is called in the PHP source file, can use the key values in the configuration file #global the same test effect as the parent # You can use the key value in the template by {#language #}, or you can access the profile key value through {$smarty. config.language} #php The source file is $smarty->getconfigvars (' language ') or $smarty->getconfigvariable (' language ') to get the key value, $smarty->getconfigvars (' language ') may also be an array*//*  The common function TPL file in the TPL file:<!--The page display content that is enclosed in the capture tag exists in capture-specified testcapture--><!--when the specified condition is reached, the {$ Smarty.capture.testCapture} output The content-->{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. {/if} {* operator can be ==,>=, etc., can be eq,ne, etc. *} {for $x =0; $x <count ($TESTARR); $x + +} {$x} {/for} {*for loop, PHP-like code *} {$x = 0} {while $x <count ($TESTARR)} {$x + +} {/while} {*while loops, also similar to PHP code. *}<!--the name and key properties do not write-->{foreach name= "Testforeach" from= $testArr key=arid item=arval}{$arId} The corresponding value is: {$arVal} <br>{$smarty. Foreach.testForeach.index} <!--(loop internal use) displays the index of the current loop, and returns -1-->{$ if the array is empty Smarty.foreach.testForeach.iteration} <!--(loop internal use) displays the current number of cycles-->{$smarty. Foreach.testForeach.first} <!-- (Loop internal use) if it is the first loop, return true-->{$smarty. Foreach.testForeach.last} <!--(loop internal use) If this is the last loop, return true-->{$ Smarty.foreach.testForeach.total} <!-(in-loop external use) shows the total number of cycles--&GT;&LT;br>{foreachelse} <!--$TESTARR array variables do not have a value (0 elements). -$TESTARR is null{/foreach}{* can also be as follows two kinds of PHP format *}{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}-<!-- The key value of the array currently looping to-->{$SECTIONARR [testsection]}-<!--the element value of the array currently looping to-->{$smarty. section.testsection.iteration}- <!--the number of current section loops, from 1--><br/>{sectionelse} $SECTIONARR is null{/section}<!-- The section loop applies to arrays of pure int key values--><!--to loop An array of loops, start specifies that the key value from the array is specified, and step specifies the difference between the key value of the next loop of the array and the current cycle key value, max Specifies the maximum number of cycles, show specifies whether to loop false if it jumps directly to the built-in variable that executes sectionelse--><!--section is the same as foreach--*//*TPL template file: {literal}<script type= "Text/javascript" >function A () {alert ("This is Script");} A (); The data in the </script>{/literal}{*literal label area will be treated as Web page HTML text, where the template ignores and does not parse all character information inside it. This feature is used to display JS, CSS, which may contain character information such as braces. When this information is in the {literal}{/literal} tab, the template engine will not parse them and display them directly. *}*///PHP File://$smarty->setdebugging (TRUE);//debug the template for subsequent calls. $smarty->getdebugging ();//Get current debug, default false//or write {debug} in template that needs debugging/* template file: smarty3.0 support for templates inheritance system, for example F1.tpl:*///PHP Page://Call template can also use this method, do some processing before output//$output = $smarty->fetch ("Index.tpl");//do something with $output Here, the content to be output is processed//echo $output;//Then the template output/*The template submits the form <form name= "input" action= "file.php" method= "POST" >action property can write directly to the PHP file name to be submitted, or do not write empty action= "" is submitted to the PHP file that called the template*///connecting to a databasemysql_connect("localhost", "root", "root");mysql_select_db("Test");$smarty->assign (' WebDir ',$_server[' Document_root ']);//$_server[' Document_root '] for the current project folder absolute path//configuration jquery src path preferably write absolute path or write to run the file can find the relative path of the jquery because to compile the file, and the compiled file and the original path environment is not the same? ><script type= "Text/javascript" src= "Http://localhost/Smarty/demo/JS/jquery-1.7.2.min.js" ></script >

PHP smarty Template engine

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.