search
HomeBackend DevelopmentPHP TutorialSmarty template engine technology 2, smarty template engine_PHP tutorial

Smarty 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>内建函数<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}

运行效果:

 

拓展内容:

 

<code><span><strong>当前索引: <span><span>{<span>$<span>smarty.section.index.index} <span>->><br/></span></span></span></span>当前索引的前一个:<span>{<span>$<span>smarty.section.index.index_prev}<span>->><br/></span></span></span></span>当前索引的下一个:<span>{<span>$<span>smarty.section.index.index_next}<span>->><br/></span></span></span></span>当前所循环的次数<span>
								<span><span>{<span>$<span>smarty.section.index.iteration}<span>->><br/></span></span></span></span>判断当前是否第一次<span><span>: <span>{<span>$<span>smarty.section.index.first}<span>->><br/></span></span></span></span></span>判断当前是否最后一次:<span>{<span>$<span>smarty.section.index.last}<span>->>
</span></span></span></span></span></span></span></span></strong></span></code>

循环的总次数:{$smarty.section.index.total}->>

 

运行效果:

示例代码:

{counter start='10' }
hr>
{counter}
hr>
{counter print=false}
hr>
{counter skip=2}
hr>
{counter}
hr>

运行效果:

基本语法:{cycle values=参数1,参数2,参数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"}
{*
变量调节器
{$text|
变量调节器名称
:参数1:参数2}
*}
{$php}
hr>
{$text|nl2br}

运行效果:

<code><span><strong>{<span>html_image <span>file=<span>"1.jpg"<span>}</span></span></span></span></strong>
				</span></code>

 

参数:file    图片资源的路径

运行效果:

 

作用:生成一个表格,将数据遍历进去

示例代码:

{html_table loop=$arr cols="3"}

参数说明:loop    要循环遍历的数组

     Cols    指定表格列数

作用:生成一组多选框

示例代码:

{html_checkboxes name = 'job'
values = $arr
checked = $arr2
output = $arr3
separator = "|"
}

参数说明: name        对应多选框中的name属性

         Values    对应多选框中你的value属性

Checked    选中指定的多选框

         Output    控制文本内容

         Separator 连接符

运行效果:

{待补充}

示例代码:

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

参数说明:values         下拉框选项的值

     Selected    指定被选中的下拉选项,注意:必须和value的值对应

         Output    输出的文本

9html_radios自定义函数

示例代码:

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

 

参数说明:values    单选框的值

         Checked    指定默认被选中的单选框

         Output    输出的文本

         Separator    连接符

运行效果:

{待补充}

实例代码:

{section loop=$arr4 name="index" }
{html_image file="./img/{$arr4[index]}.jpg"}
hr>
{/section}

 

SMARTY_DIR

  • $template_dir        模板目录    默认是:templates
  • $compile_dir        编译目录    默认是:templates_c
  • $config_dir        配置目录    默认:configs
  • $cache_dir        缓存目录    默认:cache
  • $left_delimiter    左定界符    默认:{
  • $right_delimiter    右定界符    默认:}

 

以上变量都有默认行为。

  • $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.

  • 在模板中获取数组内容:

{*多维数组*}
{$var[0]['name']}
{*
一位数组*}
{$var['name']}

  • 在模板中获取对象内容

{*获取对象属性*}
{$std->name}
hr>
{*
获取对方法*}
{$person->speak()}

Index3.php文件

$std = new StdClass();
class person{
function __construct(){}
function speak(){
echo '
你猜猜我谁
?';
}
}
$person = new person();
$std->name = '
张二明
';

 

 

概念:一般在我们项目中,有一部分数据并不是实时更新的,但是,有又必须实时访问。如果不使用缓存技术的话,每访问一次,得查询一次或者多次数据库,那么会给数据造成很高的I/O开销。会增加服务器的压力。

用户端缓存原理:

 

服务器缓存原理:

 

//开启缓存
$Smarty->caching = true;

//设置缓存文件的生命周期
$Smarty->cache_lifetime = '7200';

缓存文件由编译文件而来。

 

编译文的内容何时变化?

 

思路:设置一个生命周期只有30秒的缓存文件,定义一个变量,在模板中使用该变量。然后打开index.php.

然后修改该变量的值。等待。。。30

Smarty缓存相关细节

<code><span><strong>$Smarty<span>->isCached(<span>'index_4.tpl'<span>)</span></span></span></strong>
				</span></code>

  • 基本语法:isCached(templatesName); 检测模板文件的缓村文件是否存在
  • 参数说明:模板文件名称

<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的缓村是全局缓存,如果开启缓存,访问整个页面的数据都会被缓存,如果页面中有一些动态数据需要修改,如何处理?

如何处理页面中动态显示的数据部分呢?

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

如何解决一个模板文件,动态显示不同的内容。

实际场景:譬如一个电商网站的商品详细页,会动态的根据URL上的参数,改变该页面的内容。

那么这种情况如何实现缓存呢?

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中,我们通过设置display()第二个参数,来实现,单页面,多缓存。

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()方法设置第二个参数实现缓存集合(通过|分割)

<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>定义一个函数用于字符串替换</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>通过注册过滤器,实现模板中的字符串过滤</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>

 

通过模板继承实现页面精细化拆分

示例代码:

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>

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1117386.htmlTechArticleSmarty模板引擎技术二,smarty模板引擎 Smarty模板引擎技术 作用:载入一个php文件,将载入的文件的内容赋值给一个变量   注意:该内建函数...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment