PHP template engine Smarty A detailed introduction to _php examples

Source: Internet
Author: User
Tags create index php and php template smarty template

<?php
/*
One, what is Smarty?

Smarty is a php template engine written using PHP, which provides a separation of logic from external content, simply,
The purpose is to use the PHP programmer with the Art of separation, the use of the programmer to change the logic of the program will not affect the design of the page, the art of modifying the page will not affect the program logic, which in many people cooperation project is particularly important.

Second, Smarty Advantages:

1. Speed: A program written with Smarty can achieve maximum speed, which is relative to other template engine technology.

2. Compile: The program written by Smarty to compile into a non-template technology php file, this file uses a mixed PHP and HTML, the next time the template to access the Web request directly to the file, And no more template recompilation (without changes to the source program)

3. Caching technology: A caching technique chosen by smarty, which caches the HTML files that the user eventually sees as a static HTML page, and when the cache property of the set Smarty is true, Converting a user's Web request directly into this static HTML file during the Cachetime period of the Smarty setting 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 makes it easy to rearrange templates.

Third, not suitable to use Smarty place:

1. Content that needs to be updated in real time. For example, like the stock display, it needs to update the data frequently, and this type of program using Smarty will slow down the template processing speed.

2. Small projects. Small projects because the project is simple and art and programmer with a person's project, the use of Smarty will lose the advantages of PHP development quickly.


iv. Smarty directory structure and version
Open Smarty's official website, www.smarty.net/download.php. Download Smarty 3.1.12. tar.gz and zip are available for Linux and Windows versions, respectively.

After the download good smarty-stable-3.1.12 decompression will get a Smarty-3.1.12 folder, which has two main folders demo and Libs

The demo folder is the sample folder, which contains the default folder structure, which is the main folder where we want to write the program code. Demo in the folder name is smarty default directory structure name, you can change the corresponding property value Smarty, and then change the folder name to the name we want.
Libs is a Smarty Code source folder, generally not moving.

/libs/smarty.class.php #主文件

/libs/sysplugins/#内部plugin

/libs/plugins/#外部plugin, can be expanded freely

/demo/cahce/#放置缓存文件

/demo/configs/#放置可以载入的配置文件

/demo/templates/#放置模板文件

/demo/templates_c/#放置对模板编译后的文件

Can be extracted from the Smarty-3.1.12 folder name to the name of the project we want, demo can also be changed to what we want to specifically store the encoded folder name

2, Debugging Smarty-3.1.12

Create your own files and create index.php under the Demo folder.
Create a template in the templates directory Index.tpl
(can be almost any text file extension, commonly used is tpl,php,html, not recommended after both, because it can be accessed directly from the browser without security.) You can set the Apache httpd.conf to prevent direct access to the. tpl file. or place the Templats directory outside the site document tree. )

*/

index.php Code
Require ('.. /libs/smarty.class.php ');
$smarty = new Smarty;
In the calling template, you can output the value zhang,{} of name by {$name} for the smarty delimiter here
$smarty->assign (' name ', ' Zhang ');
Unable to execute PHP statement block in call template TPL file
$smarty->display (' Templates/index.tpl ');


/*
INDEX.TPL page Content

<body>

<span> Hello, {$name}</span>

</body>
*/

/*
Smarty compile-time processing is the source PHP file-> template file (may call multiple or multiple)-> source PHP file ...
This means that the original PHP file does not affect other processing and output. So the Smarty template file can be full HTML, or it can be part of it.

Smarty Processing Process
Smarty will PHP source files, first compiled into intermediate file (also PHP), if you enable caching, and then build a cache file based on compiled files (also PHP), the need to cache the part of all is hard coded.
Each subsequent visit accesses the compiled file (if the compiled file already exists), is called more than once (can be a single file multiple times, or multiple files multiple times), and if caching is enabled and there are cached files and there is no expiration, the cached 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 compiled file is regenerated, the cached file is necessarily regenerated.
*/

Smarty allows two special compilation settings to exist:
1, do not automatically recompile at any time (on-line phase): only if there is no compiled file of this file is generated, template files or configuration file changes, will not cause recompilation.
$smarty->setcompile_check (false);/True,false indicates that no compile file is generated without any changes to the file, except for no compiled files.
$smarty->getcompile_check ()//To get the settings for the current compilation check
2. Recompile at all times (Debug phase): Recompile at all times.
$smarty->setforce_compile (TRUE);//default false,true means recompile every time (caching is enabled every time)
$smarty->getforce_compile ()//To get the current forced compilation settings

Turn on caching
$smarty->setcaching (TRUE);
$smarty->getcaching ();//Get the current cache state, by default is False closed
$smarty->setcache_lifetime (60);//Set cache time unit seconds
{* Template file *}
{NoCache}
{$name}
{/nocache}
{* If cache is turned on, the variables placed in the NoCache tab are not cached, each time the value of the PHP source file is read *}


/*
Smarty Delimiter
In the template file, distinguishing between normal HTML code and Smarty code is a 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 identified in Smarty2, but 3.0 is not, it must be so {$ABC}, so as to better support JavaScript and CSS.
*/
$smarty->left_delimiter = "{"; Left delimiters, 2.0 attributes, 3.0 followed
$smarty->right_delimiter = "}";
/*
The delimiters are equivalent to PHP's echo, and the values in the delimiters will be output unless the assignment
The content between two * * in the Smarty TPL file is commented as
TPL file:
{* This is the template annotation content *}
*/


To set the cache directory path without setting the default "cache"
$smarty->setcachedir ("cache");
Get Cache directory path
$smarty->getcachedir ();

Set the configuration directory path without setting the default "Configs"
$smarty->setconfigdir ("configs");
Adds a configuration directory path, all paths will be saved as an array, and when the file is called, it will look in all the paths
$smarty->addconfigdir ("Configs/test");
Get an array of configuration directory paths
$smarty->getconfigdir ();

Set the plug-in directory path without setting the default "plugins"
$smarty->setpluginsdir ("plugins");
Add the plug-in directory path, all paths will be saved as an array, call the file will be found in all the paths, plugins folder in the foreground or background can be called by different rules of the function of the storage file, file name and function name according to different calling rules have different wording requirements
$smarty->addpluginsdir ("Plugins/test");
Gets an array of plug-in directory paths
$smarty->getpluginsdir ();

Set the template directory path without setting the default "templates"
$smarty->settemplatedir ("templates");
Add the template directory path, all paths will be saved as an array, and when the file is called, the files will be found in all paths
$smarty->addtemplatedir ("Templates/test");
Gets an array of template directory paths
$smarty->gettemplatedir ();

//sets the compile directory path without setting the default "Templates_c"
$smarty->setcompiledir ("Templates_c");
//Get compile directory path
$smarty-> Getcompiledir ();
/*
We can build different PHP source files folder, put the written PHP files in a certain category in a different folder.
Then create a custom config file in each folder, create a new $smarty = smarty object in config file
and then put all the different folders in the php file cache, config file, plugin, template, The compilation directory is set to the same cache, config file, plugin, template, compile directory
let all php source files in this folder refer to the profile to get the same configuration
*/


//Template variables
$arr = 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 invoked, and you can access the specific array element by {$TESTARR} or {$testArr [' a '][0]} or {$testArr. a.0} in the template that is being invoked next.
You can change the value of the passed template variable directly through {$TESTARR = "TestValue" scope= "global"} (if it does not exist, create and set it in the template), the scope property is the one that is used to label the template variable, not write
Changes in the template or created into other arrays {$TESTARR = [1,2,3]} can also {$testArr = [1, ' A ' =>2,2=>3]} can also {$TESTARR [] = 4} or other similar PHP to create an array way
The PHP source file can get the specified template variable by $smarty->gettemplatevars ("Testarr"), for example, to get the template variable changed or created in the profile, you must add the Scope property and set the value to scope when you create or change its value in the template = "global" or scope= "parent"

Class a{
function AA ($nam) {
Echo $nam;
}
}
$smarty->assign ("obj", new A);
The template variable being set is an object that can be invoked as follows in the template page to pass the class object to the template
{$obj->aa (' My name is Y ')}

Smarty can recognize template variables embedded in double quotes, as long as the variable contains only numbers, letters, and underscores. But seemingly only supports template variables that can be directly converted to strings
$smarty->assign ("Teststr", "This is Teststr");
The template can be passed {"$testStr OK!"} To access

/*
The TPL template contains templates
Template file:
{include file= "HEADER.TPL"}
HEADER.TPL content:
<span> This is the top of the content!!, welcome to you, {$name}</span>

Templates can also be in this format, including templates
{include file= "HEADER.TPL" testvar= "This is the top content!!!"}
HEADER.TPL you can use the template variables that came with the call page when using the {$testVar}
HEADER.TPL content:
<span>{$testVar}, welcome, {$name}</span>*/

/*
You can specify a sequence of variables and values in advance and place them in a configuration file and load them when they are 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

[Our]
Language = Chinese

[England]
Language = 中文版

#[china],[england] is the label, the key value of the not set label is global, as long as the profile can be invoked in the stencil, and the key value of the label can be used only if the corresponding label is specified when the configuration file is invoked
#在PHP源文件调用配置文件语句 $ Smarty->configload (' test.conf ', $sections = ' England '); The template that is invoked under this statement can use the profile and specify the key and value under which label to use through the $sections property
#$ The sections parameter can not be written, the default value is NULL, $smarty->configload (' test.conf ') uses only global key values, and cannot use the key value under the label
#在模版下通过 {config_load file= " Test.conf "section=" scope= "global"} statement invokes the configuration file
#section属性可以不写, the 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 profile statement after the current template is introduced. Or in a template that is called after the Smarty object invokes the configuration file in the PHP source file, you can use the key value
#global test effect and parent
#在模版中通过 {#language #} to use the key value in the configuration file, or you can pass the {$ Smarty.config.language} to access the configuration file key value
#PHP源文件中可以使用 $smarty->getconfigvars (' language ') or $smarty-> Getconfigvariable (' language ') to get the key value, $smarty->getconfigvars (' language ') may also be an array
*/


/*
commonly used functions in TPL files
TPL file:
<!--the page display enclosed by the capture tag exists in capture specified Testcapture-->
<!--the content can be exported through {$smarty. Capture.testcapture} When a specified condition is reached-->
{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. can also be eq,ne etc *}

{for $x =0; $x <count ($TESTARR); $x + +}
{$x}
{/for}
{*for loop, similar to PHP code *}


{$x = 0}
{while $x <count ($TESTARR)}
{$x + +}
{/while}
{*while loop, also similar to PHP code. *}


<!--name and key properties do not write-->
{foreach name= "Testforeach" from= $testArr Key=arid Item=arval}
{$arId} corresponds to the value: {$arVal}
<br>
{$smarty. Foreach.testForeach.index} <!--(used internally within loops) displays the index of the current loop, and returns -1--> if the array is empty.

{$smarty. Foreach.testForeach.iteration} <!--(used internally) displays the current number of loops-->

{$smarty. Foreach.testForeach.first} <!--(used internally within loops) if the first loop, return true-->

{$smarty. Foreach.testForeach.last} <!--(used internally within loops) if the last loop, return true-->

{$smarty. Foreach.testForeach.total} <!-(used outside the loop) shows the total number of loops-->
<br>
{Foreachelse} <!--$TESTARR array variable has no value (0 elements) executed. -->
$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 to which the current loop-->
{$SECTIONARR testsection]}-<!--The element value of the array to which the current loop is-->
{$smarty .section.testsection.iteration}-<!--the number of current section loops, from 1-->
<br/>

{Sectionelse}
$SECTIONARR is null
{/section}
<!--section loops apply to arrays of pure int-type key values-->
<!--give the loop an array to loop, start specifies to start the loop by specifying the key value from the array, and step specifies the difference between the key value of the next loop of the array and the current key value, and Max Specifies the maximum number of loops. show specifies whether to loop false to jump directly to the execution sectionelse-->
<!--section's built-in variables are the same as foreach-->

*/


/*
TPL template file:
{literal}

<script type= "Text/javascript" >
function A () {
Alert ("This is Script");
}
A ();
</script>

{/literal}
{*
The data in the literal label area will be treated as HTML text for the page, and the template will ignore and not parse all the character information inside it.
This feature is used to display JS and CSS that might contain character information such as curly braces. When the information is in the {literal}{/literal} tab, the template engine will not parse them and display it directly.
*}

*/

PHP File:
$smarty->setdebugging (TRUE);//To debug subsequent calls to the template.
$smarty->getdebugging ()//Get current debug, default False
or write to {debug} in a template that needs to be debugged

/*
Template file:

smarty3.0 supports the template inheritance system, such as
F1.TPL:
<body>

{block name= ' top '} f1.header<br/>{/block}
{Block name= ' middle '} f1.middle<br/>{/block}
{block name= ' buttom '} f1.buttom<br/>{/block}

</body>

F2.TPL:
{extends file= "F1.TPL"}
{block name= ' top '} f2.header<br/>{/block}
{Block name= ' other '} It can ' t is show <br/>{/block}
{*
If there is no block tag in the F2.TPL, or if the F2.TPL does not have the same name as the block tag in the F1.TPL, then f2.tpl the full introduction of the contents of all the contents of the display F1.TPL including the Block label, and all content in F2.TPL will be ignored
If there is a block label in the F2.TPL with the same name in F1.tpl, the contents of the block label in F2.TPL will overwrite the contents of the block label in F1.TPL when the F2.TPL is displayed, and the content will still be displayed in the format of F2.TPL when the page is displayed, f1.tpl the other Text that includes a block label with an unspecified name and its contents will be ignored and not displayed.
The contents of the block label will only overwrite the contents of the block label of the same name in the parent template, or appear in the child template, where the block label content does not appear on this page if the parent or the parent template is not called with the same name as the block label to overwrite.
This inheritance supports multiple files, multiple inheritance, which means you can inherit indefinitely.
*}


{Fetch file= "http://www.126.com" assign= "Testassign"}
{$testAssign}
{Fetch file= "http://www.126.com"}
{*fetch can refer to an external http,ftp page, such as the value of the specified assign, where the referenced content exists in a variable of the specified name, otherwise where fetch is displayed *}
*/

PHP Page:
Call templates can also use this method to do some processing before the output
$output = $smarty->fetch ("Index.tpl");
Do something with $output to handle the content that will be output
echo $output;//And then output the template

/*
Submitting a form in a template
<form name= "Input" action= "file.php" method= "POST" >
The action attribute can write directly to the PHP file name to be submitted to, or do not write empty action= "" is submitted to the PHP file calling the template
*/


Connecting to a database
mysql_connect ("localhost", "root", "root");
mysql_select_db ("test");
$smarty->assign (' WebDir ', $_server[' document_root '),//$_server[' Document_root '] is the absolute path to the current project folder
To configure the SRC path of jquery It is best to write an absolute path or write to run a file to find the relative path to the jquery because the compiled file is compiled to compile and the file is not the same as the original PATH environment
?>
<script type= "Text/javascript" src= "Http://localhost/Smarty/demo/JS/jquery-1.7.2.min.js" ></script>

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.