


Smarty template engine technology 2, smarty template engine_PHP tutorial
Jul 12, 2016 am 08:55 AMSmarty template engine technology 2, smarty template engine
Smarty template engine technology
Function: Load a php file and assign the content of the loaded file to a variable
Note: This built-in function can only be used in 2.0. If used, SmartyBC.class.php must be instantiated.
Sample code:
Index.php
include 'Smarty/SmartyBC.class.php';
//InstantiationSmartyClass
$Smarty = new SmartyBC();
$Smarty->assign('name','Xiao Ming');
$Smarty->display('index.tpl');
index.tpl
<code><span><strong><em><span>{*<span>include_php</span></span>內(nèi)建函數(shù)<span>*}<br/></span></em><span>{<span>include_php <span>file=<span>"date.php" <span>assign=<span>"date"<span>}<br/>{<span>$<span>date}</span></span></span></span></span></span></span></span></span></strong> </span></code>
Function: When the built-in functions of Smarty are not enough, you can expand the functions by inserting the built-in function.
Basic syntax: Create an index.php file
insert_Custom function name($arg){
echo $arg[variable defined in template]
}
Index.tpl file
{insert name=Custom function name Custom parameters... }
Sample code:
Index.php
function insert_func($arg){
echo $arg['title'];
}
function insert_date($arg){
echo $arg['say']."The weather is great today. , the current time is ".date('Y-m-d H:i:s',time());
echo '
';
echo $arg['zhangsan']."The weather is great today. The time is now".date('Y-m-d H:i:s',time());
}
index.tpl template
{insert name="func" title='PHP is the best language in the world '}
< hr>
{insert name="date" say='Lao Wang said:' zhangsan='Hahaha:'}
Sample code:
{if $age >= 18}
This person is not a minor
{elseif $age == '14'}
This person is 14 years old
{else}
This person is a minor
{/if }
Sample code:
<b>inSmarty we use {ldelim}if{rdelim}Perform conditional judgmentb>
Function: Any content in this tag will not be parsed by the Smarty template engine
Sample code:
{literal}
{*Hi, I am an annotator *}
{assign var='age' value="14"}
{/literal}
Operation effect:
Function: Native PHP code can be used in this tag.
Sample code:
{*PHPBuilt-in functions*}
{php}
echo date('Y-m-d h:i:s',time());
echo '<br>';
echo "I am at php Contents in built-in functions";
{/php}
Operation effect:
7. stripbuilt-in function
Function: Remove spaces and newlines
Sample code:
{strip}
<table>
<tr >
<td>1td>
<td>2td>
<td>3td> ;
<td>4td>
<td>5td>
tr>
table>
{/strip}
Before use:
After use:
8, section, sectionelseBuilt-in function (two-dimensional array, )
Function: Traverse the array
Basic usage:
{section loop=$arr name="index"}
{$ arr[index]}
<br>
{/section}
Parameter details: loop needs to traverse the array
Name The index of the current loop
Extended use 1: Use start step max
{section loop=$arr1 name="index" start="0" step="1" max="5"}
{$arr1[index]}
<br>
{/section}
- Parameter details: start The starting index of the loop
Step The amount added each time through the loop
Max the maximum number of loops
Extended use 2: sectionelse
Function: Determine whether the looped array is empty. If it is empty, execute the following content.
Example code:
{*sectionBuilt-in functions*}
{section loop=$arr1 name="index" start="0" step ="1" max="5"}
{$arr1[index]}
<br>
{sectionelse}
<b>): There is no array or the array is emptyb>
{/section}
- Traverse a two-dimensional array
Example code:
Index.php
$arr3 = array(array('name'=>'小明','age'=>25,'sex'=>'未知'),
array('name'=>'老王','age'=>26,'sex'=>'男'),
array('name'=>'老李','age'=>27,'sex'=>'你猜')
);
Index.tpl
{section loop=$arr3 name="index" }
{$arr3[index]['name']} |
{$arr3[index]['age']} |
{$arr3[index]['sex']} |
<hr/>
{/section}
運(yùn)行效果:
?
拓展內(nèi)容:
?
<code><span><strong>當(dāng)前索引: <span><span>{<span>$<span>smarty.section.index.index} <span>->><br/></span></span></span></span>當(dāng)前索引的前一個:<span>{<span>$<span>smarty.section.index.index_prev}<span>->><br/></span></span></span></span>當(dāng)前索引的下一個:<span>{<span>$<span>smarty.section.index.index_next}<span>->><br/></span></span></span></span>當(dāng)前所循環(huán)的次數(shù)<span> <span><span>{<span>$<span>smarty.section.index.iteration}<span>->><br/></span></span></span></span>判斷當(dāng)前是否第一次<span><span>: <span>{<span>$<span>smarty.section.index.first}<span>->><br/></span></span></span></span></span>判斷當(dāng)前是否最后一次:<span>{<span>$<span>smarty.section.index.last}<span>->> </span></span></span></span></span></span></span></span></strong></span></code>
循環(huán)的總次數(shù):{$smarty.section.index.total}->>
?
運(yùn)行效果:
示例代碼:
{counter start='10' }
<hr>
{counter}
<hr>
{counter print=false}
<hr>
{counter skip=2}
<hr>
{counter}
<hr>
運(yùn)行效果:
基本語法:{cycle values=參數(shù)1,參數(shù)2,參數(shù)3}
?
示例代碼:
{*cycleRealize color change of each row*}
<hr>
<table width="100%">
<tr style="background-color: {cycle values="red,green,yellow"}" >
<td>My first {counter start='1' skip='1'} cycletd>
tr>
<tr style="background-color: {cycle values="red,green,yellow"}">
<td>I The {counter} looptd>
tr>
<tr style="background-color: {cycle values="red,green,yellow"}">
<td>Myth{counter} cycletd>
tr>
<tr style="background-color: {cycle values="red,green,yellow"}">
<td> Myth{counter}Looptd>
tr>
< tr style="background-color: {cycle values="red,green,yellow"}">
<td> My first {counter} looptd>
tr>
<tr style="background-color: {cycle values="red,green,yellow"}">
<td> My number{counter} cyclestd>
tr>
< ;/table>
{debug}
Operation effect:
Function: Capture the contents of a file and assign it to a variable
Sample code:
{fetch file="shi.txt" assign="text"}
{fetch file="date.php" assign="php"}
{*變量調(diào)節(jié)器
{$text|變量調(diào)節(jié)器名稱:參數(shù)1:參數(shù)2}
*}
{$php}
<hr>
{$text|nl2br}
運(yùn)行效果:
<code><span><strong>{<span>html_image <span>file=<span>"1.jpg"<span>}</span></span></span></span></strong> </span></code>
?
參數(shù):file????圖片資源的路徑
運(yùn)行效果:
?
作用:生成一個表格,將數(shù)據(jù)遍歷進(jìn)去
示例代碼:
{html_table loop=$arr cols="3"}
參數(shù)說明:loop????要循環(huán)遍歷的數(shù)組
???? Cols????指定表格列數(shù)
作用:生成一組多選框
示例代碼:
{html_checkboxes name = 'job'
values = $arr
checked = $arr2
output = $arr3
separator = "|"
}
參數(shù)說明: name????????對應(yīng)多選框中的name屬性
???????? Values????對應(yīng)多選框中你的value屬性
Checked????選中指定的多選框
???????? Output????控制文本內(nèi)容
???????? Separator 連接符
運(yùn)行效果:
{待補(bǔ)充}
示例代碼:
<code><span><strong><<span>select <span>style=<span>"<span>width: <span>100<span>%;<span>"<span>><br/> <span>{<span>html_options <span>values = <span>$<span>arr<br/> selected = <span>'GO'<br/> <span>output = <span>$<span>arr3<br/> }<br/><span></<span>select<span>></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></strong><span> </span></span></code>
參數(shù)說明:values???? ????下拉框選項(xiàng)的值
???? Selected????指定被選中的下拉選項(xiàng),注意:必須和value的值對應(yīng)
???????? Output????輸出的文本
9、html_radios自定義函數(shù)
示例代碼:
<code><span><strong>{<span>html_radios <span>values = <span>$<span>arr<br/> checked = <span>'nodejs'<br/> <span>output = <span>$<span>arr3<br/> separator = <span>"|"<br/><span>}</span></span></span></span></span></span></span></span></span></span></strong> </span></code>
?
參數(shù)說明:values????單選框的值
???????? Checked????指定默認(rèn)被選中的單選框
???????? Output????輸出的文本
???????? Separator????連接符
運(yùn)行效果:
{待補(bǔ)充}
實(shí)例代碼:
{section loop=$arr4 name="index" }
{html_image file="./img/{$arr4[index]}.jpg"}
<hr>
{/section}
?
SMARTY_DIR
- $template_dir????????模板目錄????默認(rèn)是:templates
- $compile_dir????????編譯目錄????默認(rèn)是:templates_c
- $config_dir????????配置目錄????默認(rèn):configs
- $cache_dir????????緩存目錄????默認(rèn):cache
- $left_delimiter????左定界符????默認(rèn):{
- $right_delimiter????右定界符????默認(rèn):}
?
以上變量都有默認(rèn)行為。
- $caching Whether to enable caching
- $cache_lifetime Cache life cycle: Default 3600s
- $debugging Enable debugging template
- $php_handling Is it allowed to introduce php in the template?
3, common methods
- assign passes variables to the template
- assignByRef Assign variables to template files (pass by reference)
- append Append variables
$Smarty->append('var1','Xiao Ming');
$Smarty->append ('var1','25');
$Smarty->append('var1','Male');
- appendByRef appends different data to the array variable of the template (passed by reference)
- clearAllAssign Clear all variables in the template
$Smarty->clearAllAssign(); // Clear all template variables
- clearAssign clears the specified variable
$Smarty->clearAssign('title') ;
- clearCache Clear cache
- configLoad Configuration loading
$Smarty->configLoad('config.conf','class2');
- clearConfig Clear configuration content
$Smarty->clearConfig('name') ;
- display Specify rendering template
$Smarty->display('index_3.tpl');
Load template file
Rendering template
Show template
- fetch captures the template but does not output it
Load template file
Render (replace tags with php code) template file
We can implement static technology through fetch.
Index_3.php file
/*
* If any Static files are loaded, and if there is no static file, a static file is generated.
* */
if(!is_file( './html/index_3.html')){
$html = $Smarty->fetch('index_3.tpl');
file_put_contents('./html/index_3.html',$html);
echo ' There are no static files here';
include "./html/index_3.html";
}else{
echo 'There are static files here ';
include "./html/index_3.html";
}
[To be added]
- templateExists determines whether the template file exists
if($Smarty->templateExists('index_4.tpl')){
$Smarty->display('index_3.tpl');
}else{
echo ' Diaoyou, the template file is not there~';
}
Added: How to read array, object in smarty template.
- 在模板中獲取數(shù)組內(nèi)容:
{*多維數(shù)組*}
{$var[0]['name']}
{*一位數(shù)組*}
{$var['name']}
- 在模板中獲取對象內(nèi)容
{*獲取對象屬性*}
{$std->name}
<hr>
{*獲取對方法*}
{$person->speak()}
Index3.php文件
$std
= new StdClass();
class person{
function __construct(){}
function speak(){
echo '你猜猜我誰?';
}
}
$person = new person();
$std->name = '張二明';
?
?
概念:一般在我們項(xiàng)目中,有一部分?jǐn)?shù)據(jù)并不是實(shí)時更新的,但是,有又必須實(shí)時訪問。如果不使用緩存技術(shù)的話,每訪問一次,得查詢一次或者多次數(shù)據(jù)庫,那么會給數(shù)據(jù)造成很高的I/O開銷。會增加服務(wù)器的壓力。
用戶端緩存原理:
?
服務(wù)器緩存原理:
?
//開啟緩存
$Smarty->caching = true;
//設(shè)置緩存文件的生命周期
$Smarty->cache_lifetime = '7200';
緩存文件由編譯文件而來。
?
編譯文的內(nèi)容何時變化?
?
思路:設(shè)置一個生命周期只有30秒的緩存文件,定義一個變量,在模板中使用該變量。然后打開index.php.
然后修改該變量的值。等待。。。30
Smarty緩存相關(guān)細(xì)節(jié)
<code><span><strong>$Smarty<span>->isCached(<span>'index_4.tpl'<span>)</span></span></span></strong> </span></code>
- 基本語法:isCached(templatesName); 檢測模板文件的緩村文件是否存在
- 參數(shù)說明:模板文件名稱
<code><span><span><strong><em>//</em></strong></span><span><strong><em>清除所有緩存<br/><span><span>$<span>Smarty->clearAllCache();<br/><span>//</span></span></span><span>清楚某模板緩存文件<br/></span></span></em><span>$Smarty<span>->clearCache(<span>'index_4.tpl'<span>);</span></span></span></span></strong> </span></span></code>
?
在Smarty的緩村是全局緩存,如果開啟緩存,訪問整個頁面的數(shù)據(jù)都會被緩存,如果頁面中有一些動態(tài)數(shù)據(jù)需要修改,如何處理?
如何處理頁面中動態(tài)顯示的數(shù)據(jù)部分呢?
<code><span><strong><span>$Smarty<span>->assign(<span>'shige'<span>,<span>'</span></span></span></span></span>《再別康橋》<span>'<span>,<span>true<span>);</span></span></span></span></strong> </span></code>
<code><span><strong>{<span>nocache<span>}<br/> {<span>$<span>title}<br/>{/<span>nocache<span>}</span></span></span></span></span></span></strong> </span></code>
如何解決一個模板文件,動態(tài)顯示不同的內(nèi)容。
實(shí)際場景:譬如一個電商網(wǎng)站的商品詳細(xì)頁,會動態(tài)的根據(jù)URL上的參數(shù),改變該頁面的內(nèi)容。
那么這種情況如何實(shí)現(xiàn)緩存呢?
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=1
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=2
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=3
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=250
?
在Smarty中,我們通過設(shè)置display()第二個參數(shù),來實(shí)現(xiàn),單頁面,多緩存。
11、緩存集合
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=1&cate_id=15
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=1&cate_id=15
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=1&cate_id=15
http://localhost:63354/Smarty/Smarty02/index5.php?goods_id=1&cate_id=15
我們通過給display()方法設(shè)置第二個參數(shù)實(shí)現(xiàn)緩存集合(通過|分割)
<code><span><span><strong>$Smarty</strong></span><span><strong>->display(<span>'index_5.tpl'<span>,<span>$_GET<span>[<span>'goods_id'<span>].<span>'|'<span>.<span>$_GET<span>[<span>'cate_id'<span>]);</span></span></span></span></span></span></span></span></span></span></span></span></strong> </span></span></code>
?
五、過濾器
示例代碼:
<code><span><strong><span>//</span><span>定義一個函數(shù)用于字符串替換</span><span> </span></strong></span></code>
<code><span><strong><span>function <span>check<span>(<span>$tpl_output<span>, <span>$smarty<span>){<br/> <span>$tpl_output <span>= <em>str_replace</em>(<span>'</span></span></span></span></span></span></span></span></span></span>蒼井空<span><span>'<span>,<span>'</span></span></span>張某某<span>'<span>,<span>$tpl_output<span>);<br/> <span>return <span>$tpl_output<span>;<br/>} </span></span></span></span></span></span></span></span></strong></span></code>
<code><span><strong><span>//</span><span>通過注冊過濾器,實(shí)現(xiàn)模板中的字符串過濾</span></strong><span><strong><br/><span>$Smarty<span>->registerFilter(<span>"output"<span>,<span>"check"<span>);</span></span></span></span></span></span></strong> </span></span></code>
?
通過模板繼承實(shí)現(xiàn)頁面精細(xì)化拆分
示例代碼:
Parent.tpl文件
<code><span><span><strong>{<span>extends <span>file=<span>"parent.tpl"<span>}<br/>{<span>block <span>name=<span>'content'<span>}<br/> </span></span></span></span></span></span></span></span></strong></span><span><strong>偶哈呦,哈哈哈哈<br/> <span><<span>hr<span>><br/><span>{/<span>block<span>}</span></span></span></span></span></span></strong> </span></span></code>
Child.tpl文件
<code><span><span><strong>{<span>extends <span>file=<span>"parent.tpl"<span>}<br/>{<span>block <span>name=<span>'content'<span>}<br/> </span></span></span></span></span></span></span></span></strong></span><span><strong>偶哈呦,哈哈哈哈<br/> <span><<span>hr<span>><br/><span>{/<span>block<span>}</span></span></span></span></span></span></strong> </span></span></code>
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

In September 23, the paper "DeepModelFusion:ASurvey" was published by the National University of Defense Technology, JD.com and Beijing Institute of Technology. Deep model fusion/merging is an emerging technology that combines the parameters or predictions of multiple deep learning models into a single model. It combines the capabilities of different models to compensate for the biases and errors of individual models for better performance. Deep model fusion on large-scale deep learning models (such as LLM and basic models) faces some challenges, including high computational cost, high-dimensional parameter space, interference between different heterogeneous models, etc. This article divides existing deep model fusion methods into four categories: (1) "Pattern connection", which connects solutions in the weight space through a loss-reducing path to obtain a better initial model fusion

The importance and role of the define function in PHP 1. Basic introduction to the define function In PHP, the define function is a key function used to define constants. Constants will not change their values ??during the running of the program. Constants defined using the define function can be accessed throughout the script and are global. 2. The syntax of define function The basic syntax of define function is as follows: define("constant name","constant value&qu

Written above & The author’s personal understanding is that image-based 3D reconstruction is a challenging task that involves inferring the 3D shape of an object or scene from a set of input images. Learning-based methods have attracted attention for their ability to directly estimate 3D shapes. This review paper focuses on state-of-the-art 3D reconstruction techniques, including generating novel, unseen views. An overview of recent developments in Gaussian splash methods is provided, including input types, model structures, output representations, and training strategies. Unresolved challenges and future directions are also discussed. Given the rapid progress in this field and the numerous opportunities to enhance 3D reconstruction methods, a thorough examination of the algorithm seems crucial. Therefore, this study provides a comprehensive overview of recent advances in Gaussian scattering. (Swipe your thumb up

In today's software development field, Go language and JavaScript are widely used in different fields and scenarios. As a statically typed, compiled language, Go language is suitable for back-end services and system-level programming; while JavaScript is a dynamically typed, interpreted language, mainly used for front-end development and interaction design. Although there are obvious differences between the two in terms of syntax and operating environment, the communication and integration between them have also become a topic of concern to software developers. With the development trend of separation of front-end and back-end, front-end

Regarding PPT masking, many people must be unfamiliar with it. Most people do not understand it thoroughly when making PPT, but just make it up to make what they like. Therefore, many people do not know what PPT masking means, nor do they understand it. I know what this mask does, and I don’t even know that it can make the picture less monotonous. Friends who want to learn, come and learn, and add some PPT masks to your PPT pictures. Make it less monotonous. So, how to add a PPT mask? Please read below. 1. First we open PPT, select a blank picture, then right-click [Set Background Format] and select a solid color. 2. Click [Insert], word art, enter the word 3. Click [Insert], click [Shape]

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
