PHP template engine smarty Details _php Tutorial

Source: Internet
Author: User
Tags php template

PHP template engine Smarty Detailed description


This article mainly introduces the PHP template engine Smarty Detailed introduction, this article explains what is smarty, smarty advantages, not suitable for use Smarty Place, Smarty directory structure and version, the need for friends can refer to the next

  

/*

First, what is Smarty?

Smarty is a template php template engine written in PHP, which provides the separation of logic and external content, simply speaking,

The purpose is to use the PHP programmer with the Art of separation, the use of programmers to change the logic of the program will not affect the design of the page, the artist re-modify the page does not affect the program logic, which in the multi-person cooperation project is particularly important.

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 run time, this file is a mixture of PHP and HTML, the next time you access the template, the Web request will be converted directly to this file, and no longer template recompilation ( 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 places:

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 the official website of Smarty, www.smarty.net/download.php. Download Smarty 3.1.12. There are tar.gz and zip respectively for Linux and Windows versions.

After downloading the smarty-stable-3.1.12 extract will get a Smarty-3.1.12 folder with two main folders in demo and Libs.

The demo folder is a sample folder containing the default folder structure, which 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, free to expand

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

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

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

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

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

2, commissioning 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 and 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 Code

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

$smarty = new Smarty;

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

  

  

Hello, {$name}

  

  

*/

/*

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 based on the compilation of files 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 two special compilation settings to exist:

1, do not automatically recompile at any time (on-line stage): Only the compilation file without the file is generated, the template file or configuration file changes, will not cause recompilation.

$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 a file change.

$smarty->getcompile_check ();//Get settings for the current compilation check

2. Recompile at any time (Debug phase): Recompile at any time.

$smarty->setforce_compile (TRUE);//The default is false,true to recompile each time (cache is enabled, each time it is re-cached)

$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 Delimiter

In the template file, the distinction between ordinary HTML code and Smarty code is delimited by 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 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 equivalent to the echo of PHP, and the value in the delimiter will be output, unless an assignment such as an operation

Smarty the contents of the two * * in the delimiter in the TPL file are commented content such as

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 to create a new $smarty = Smarty object in the config file

Then put all the different folders of PHP file cache, config file, plugin, template, compile directory are set to the same cache, config file, plugin, template, compile directory

Allow all PHP source files under this folder to refer to the configuration file 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 to be called, which can be accessed through {$TESTARR} or {$testArr [' a '][0]} or {$testArr. a.0} in the next called template.

In the template can be directly through {$TESTARR = "TestValue" scope= "global"} to change the value of the passed-over templates variable (if it does not exist in the template to create and set up the model variable), the Scope property is the label template variable use of the non-writable

Changing or creating a different array {$TESTARR = [4]} in a template can also {$testArr = [1, ' A ' =>2,2=>3]} or you can create an array in the form of {$TESTARR []

PHP source files can get the specified template variables by $smarty->gettemplatevars ("Testarr"), such as to get template variables that have been altered or created in the templates, and to create or change their values in a template, you must add the Scope property and set the value to scope = "global" or scope= "parent"

Class a{

function AA ($nam) {

Echo $nam;

}

}

$smarty->assign ("obj", new A);

When you set the template variable to be an object, the template page can be called as follows, which is also used when the template is passed to the class object.

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

Smarty can identify template variables that are 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 templates

Template file:

{include file= "HEADER.TPL"}

HEADER.TPL content:

This is the top of the content!!, welcome, {$name}

Template contains templates can also be in this format

{include file= "HEADER.TPL" testvar= "This is the top content!!!"}

HEADER.TPL can be used to include template variables when the call page is included through {$testVar}

HEADER.TPL content:

{$testVar}, welcome, {$name}

*/

/*

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 = 中文版

#[china],[england] is a label, the key value of the label is not set to global, as long as the configuration file can be called to use in the template, set the label's key value can only be used when the configuration file is called to specify the corresponding label

#在PHP源文件调用配置文件语句 $smarty->configload (' test.conf ', $sections = ' England '); The template that is called below the statement can use the configuration file through the The sections property specifies the key and value under which label to use

# $sections parameter can not be written, default value is null, $smarty->configload (' test.conf ') only uses global key value, but cannot use key value under label

#在模版下通过 {config_load file= "test.conf" section= "China" scope= "global"} statement invoke configuration file

#section属性可以不写, the default is that the Null,scope property must be written {config_load file= "test.conf" scope= "global"}

#section属性可赋三种值

#local only the current template can use the configuration file

#parent the key values in this profile are available only in the template that is included in the current template after the profile statement is introduced, or in a template that is called after the Smarty object calls the profile in the PHP source file

#global test effect is the same as parent

#在模版中通过 {#language #} to use the key value, or you can access the profile key value by {$smarty. Config.language}

#PHP源文件中可以使用 $smarty->getconfigvars (' language ') or $smarty->getconfigvariable (' language ') to get the key value, $smarty- Getconfigvars (' language ') is also possible to get 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.

{/if}

{* operator can be ==,>=, etc., can be eq,ne, etc. *}

{for $x =0; $x

{$x}

{/for}

{*for loop, PHP-like code *}

{$x = 0}

{While $x

{$x + +}

{/while}

{*while loops, also similar to PHP code. *}

  

{foreach name= "Testforeach" from= $testArr Key=arid Item=arval}

{$arId} corresponds to the value: {$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}

{* 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}-

{$SECTIONARR [testsection]}-

{$smarty. section.testsection.iteration}-

  

{Sectionelse}

$SECTIONARR is null

{/section}

  

  

  

*/

/*

TPL template file:

{literal}

  

{/literal}

{*

The data in the literal label area is treated as a 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 Files:

$smarty->setdebugging (TRUE);//debug the template for subsequent calls.

$smarty->getdebugging ();//Get current debugging, default False

or write {debug} in a 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 the F2.TPL, or F2.TPL does not have the same named block tag in the F1.TPL, then F2.TPL fully introduces the contents of all contents including the block tag in F1.tpl, and all content in F2.TPL will be ignored

If there is a block tag with the same name in the F2.TPL in the F1.TPL, the contents of the block tag in the F1.TPL will be overwritten with the contents of the block tag in F2.tpl when the F2.TPL is displayed, and the content will still be displayed in F2.TPL format when the F1.TPL page is displayed, F2.tpl other A block tag with text that includes no name and its contents will be ignored and not displayed.

The contents of the block tag will only overwrite the contents of the block tag with the same name in the parent template, or appear in the sub-template, and the block label content does not appear on this page if there is no call to the parent template or the parent template that does not have the same name as the block tag that you want to overwrite.

This inheritance supports multiple files, multiple inheritance, which means that 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, in which 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 here to process the content that will be output

echo $output;//Then output the template

/*

Submit a form in a template

The Action property can be written directly to the PHP file name to be submitted to, or not the empty action= "" is submitted to the PHP files that called 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 a file to run to find the relative path to the jquery because the compiled file will be compiled and the original path environment is not the same

?>

  

http://www.bkjia.com/PHPjc/1006579.html www.bkjia.com true http://www.bkjia.com/PHPjc/1006579.html techarticle php Template engine smarty Details This article mainly introduces the PHP template engine Smarty Detailed introduction, this article explains what is smarty, smarty advantages, not suitable for use smarty place, 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.