search
HomeBackend DevelopmentPHP TutorialPHP视图引擎Smarty的简单使用

PHP视图引擎Smarty的简单使用

       什么是模版引擎 
   
 不知道从什么时候开始,有人开始对 HTML 内嵌入 Server Script 觉得不太满意。然而不论是微软的 ASP 或是开放源码的 PHP,都是属于内嵌 Server Script 的网页伺服端语言。因此也就有人想到,如果能把程序应用逻辑 (或称商业应用逻辑) 与网页呈现 (Layout) 逻辑分离的话,是不是会比较好呢? 
   
 其实这个问题早就存在已久,从交互式网页开始风行时,不论是 ASP 或是 PHP 的使用者都是身兼程序开发者与视觉设计师两种身份。可是通常这些使用者不是程序强就是美工强,如果要两者同时兼顾,那可得死掉不少脑细胞... 
   
 所以模版引擎就应运而生啦!模版引擎的目的,就是要达到上述提到的逻辑分离的功能。它能让程序开发者专注于资料的控制或是功能的达成;而视觉设计师则可专注于网页排版,让网页看起来更具有专业感!因此模版引擎很适合公司的网站开发团队使用,使每个人都能发挥其专长! 

       Smarty是一个使用PHP写出来的模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。简单的讲,目的就是要使PHP程序员同前端人员分离,使程序员改变程序的逻辑内容不会影响到前端人员的页面设计,前端人员重新修改页面不会影响到程序的程序逻辑,这在多人合作的项目中显的尤为重要。

下面记录一下关于Smarty的基础使用:

1、安装Smarty

首先从Smarty官网下载:http://www.smarty.net/

然后解压出来,并且文件目录结构,修改为如下:(方面使用而已)

可以将其他不用的文件删除。

2、配置Smarty并进行简单使用

       下面我们创建如下类似目录结构(这要包括cache Smarty的缓存目录、template_c Smarty的编译结果目录、tpl Smarty的视图模板目录 —— 这配置Smarty的过程中会引用这些目录)

       在 test.php 文件中 配置Smarty:(记得先导入Smarty的主文件 Smarty.class.php)

<?php require('../smarty-3.1.29/libs/Smarty.class.php');
	$smarty = new Smarty();

	//Smarty的口诀“五配置方法”
	//五配置的介绍
	$smarty->left_delimiter = "{"; //左定界符
	$smarty->right_delimiter = "}"; //右定界符
	$smarty->template_dir = "tpl"; //html模板的地址            //要把对应的目录创建好
	$smarty->compile_dir = "template_c"; //模板编译生成的文件
	$smarty->cache_dir = "cache"; //缓存
	//以下是开启缓存的另两个配置。因为通常不用smarty的缓存机制,所以此项为了解。
	$smarty->caching = true; //开启缓存
	$smarty->cache_lifetime = 120; //缓存时间

	//在smarty模板变量的赋值
	$smarty->assign('articletitle', '文章标题'); //注册到smarty模板里面去(变量名,变量值)

	//展示编写好的模板,该函数能对模板进行编译和展示
	$smarty->display('test.tpl');
?>

       通过 $smarty->assign('articletitle', '文章标题'); 将变量articletitle注册到Smarty模板。并且使用视图 test.tpl (当然后缀名可以为 .html,实际上网页开发也是用 .html)。

       test.tpl(在tpl目录下创建)

{$articletitle} <br>

       这样我们就能使用刚注册到Smarty模板的变量 articletitle 了。

       访问过程为:执行test.php文件,创建Smarty对象,配置Smarty,将变量articletitle 注册到Smarty,选择视图进行显示(Smarty会对视图进行编译将视图中以{}为定界符包起来的变量解析为变量的值,然后显示在页面)。这样实现了界面层与逻辑层的分离。逻辑层通过注册数据到Smarty,通过控制显示对应的界面,界面就可以使用逻辑层返回的数据进行显示。

3、Smarty变量的访问

3.1、访问一维数组

$arr = array('title'=>'smarty的学习', 'author' => '小明');
$smarty->assign('arr', $arr);

在视图中(下面这两种方式都可以正常访问):

{$arr.title} {$arr.author} <br>
{$arr['title']} {$arr['author']} <br>

3.2、访问二维数组

 

 

$arr2 = array('articlecontent'=>array('title'=>'smarty的学习', 'author' => '小明'));
$smarty->assign('arr2', $arr2);

在视图中:

{$arr2['articlecontent']['title']} {$arr2['articlecontent']['author']} <br>

3.3、访问对象

	class My_Object {
		function meth1($params) {
			return $params[0].'已经'.$params[1];
		}
	}
	$myobj = new My_Object();
	$smarty->assign("myobj",$myobj);

在视图中:

输出对象
{$myobj->meth1(array('苹果','熟了'))}
<br><br>

3.4、访问php其他数据类型

       访问php其他数据类型,与在php中使用访问类似,这里就不再给出案例。

(注:对于变量的访问,可以将访问变量的语句嵌套在 html 代码中)

4、条件判断

4.1、基本句式(视图中使用(或者说是html界面))

 

{if $name eq "a1"}
	Welcome Sir.
{elseif $name eq "a2"}
	Welcome Ma'am.
{else}
	Welcome, whatever you are.
{/if}

4.2、条件修饰符有很多,简单的有:eq(==)   neq(!=)  gt(>)  lt(

4.3、修饰词时必须和变量或常量用空格开

5、Smarty的循环

5.1、section

section、sectionelse 功能多,参数多。是Smarty用来做循环操作的函数之一。

基本属性有name和loop

       除了name和loop属性外,还有以下属性

start   循环执行的初始位置。如果该值为负数,开始位置从数组的尾部算起。例如:如果数组中有7个元素,指定start为-2,那么指向当前数组的索引为5.非法值(超过了循环数组的下限)将被自动调整为最接近的合法值。

step    该值决定循环的步长。例如指定step = 2将只遍历下标为0、2、4等元素。如果step为负值,那么遍历数组的时候从后向前遍历。

max   设定循环最大执行次数。

show    决定是否显示该循环。

案例:

test.php中

//在smarty模板变量的赋值
	$articlelist = array(
			array(
					"title" => "第一篇文章",
					"author" => "小王",
					"content" => "第一篇文章该写点啥呢"
				),
			array(
					"title" => "第二篇文章",
					"author" => "小李",
					"content" => "又写了一篇不知所云的文章"
				)
		);
	$smarty->assign("articlelist", $articlelist);

视图中:

<!-- section 在smarty中函数的一种,函数以</函数名>结尾 -->
section循环<br>
{section name = article loop = $articlelist max=1}
	{$articlelist[article].title}
	{$articlelist[article].author}
	{$articlelist[article].content}
<br>
{/section}
<br>

5.2、foreach循环(与PHP中的foreach类似)

视图中:

foreach循环<br>
{foreach item = article from = $articlelist}
	{$article.title}
	{$article.author}
	{$article.content}
<br>
{foreachelse} <!-- 当数组为空是 显示下面的这句话-->
当前没有文章
{/foreach}
<br>

foreach循环——PHP形式<br>
{foreach $articlelist as $article}
	{$article.title}
	{$article.author}
	{$article.content}
<br>
{foreachelse}
当前没有文章
{/foreach}
<br>

建议使用类似PHP形式的foreach循环,便于记忆使用。

6、Smarty模板的引用

       将其他模板引入到当前模板:使用include

在当前模板中使用,例如:

创建入口文件 test03.php

<?php require('../smarty-3.1.29/libs/Smarty.class.php');
	$smarty = new Smarty();

	//Smarty的自编口诀“五配置方法”
	//五配置的介绍
	$smarty->left_delimiter = "{"; //左定界符
	$smarty->right_delimiter = "}"; //右定界符
	$smarty->template_dir = "tpl"; //html模板的地址            //要把对应的目录创建好
	$smarty->compile_dir = "template_c"; //模板编译生成的文件
	$smarty->cache_dir = "cache"; //缓存
	//以下是开启缓存的另两个配置。因为通常不用smarty的缓存机制,所以此项为了解。
	$smarty->caching = true; //开启缓存
	$smarty->cache_lifetime = 120; //缓存时间

	//展示编写好的模板,该函数能对模板进行编译和展示
	$smarty->display('test03.tpl');
?>

创建当前模板 test03.tpl

{include file="header.tpl" sitename="哈哈"} <!-- include还有其他属性(包括 sitename),其他属性的名称可以自定义,它的值可以传给引入的模板--> <!-- 这些自定义的属性仅仅只能在引入的文件中使用,如sitename属性只能在header.tpl中使用-->

其中被引入的模板为 header.tpl,属性sitename是自定义的,可以按照PHP的命名方式进行命名。表示传递到被引入的模板的变量,可以在被引入的模板中使用该变量。

       header.tpl

头文件——{$sitename}

7、变量调节器

7.1、首字母大写 capitalize

如:{$articleTitle|capitalize}

7.2、字符串连接 cat
如:{$articleTitle|cat:" aaaa"}

7.3、日期格式化 date_format

如:{$yesterday|date_format}

      {$yesterday|date_format:" :"%A, %B %e, %Y %H:%M:%S"}

7.4、为未赋值或为空的变量指定默认值default

如:{$articleTitle|default:"no title"}

7.5、转码escape

       用于html转码,url转码,在没有转码的变量上转换单引号,十六进制转码,十六进制美化,或者javascript转码。默认是html转码。

7.6、小写lower 大写upper

将变量字符串小(大)写

如:{$articleTitle|lower}   {$articleTitle|upper}

7.7、所有的换行符将被替换成
nl2br功能同PHP中nl2br()函数一样

如:{$articleTitle|nl2br}

7.8、其他函数

可以参见手册,原则上应该通过php直接处理完再赋值到smarty变量里,少用smarty函数。

8、使用php内置函数

基本格式为: {参数1|php内置函数名:参数2:参数3:...}

案例如下:

	$smarty->assign('time',time());

	$smarty->assign('str', 'abcdefg');

视图中:

 

Smarty函数的使用(使用PHP的内置函数)date -1<br>
在Smarty中函数的调用 | 函数名 ,其中“|”前为函数的第一个参数,函数名后为函数的第二个参数<br>
而在php中的date函数,第一个参数为时间戳,第二个参数为时间的格式。所以在使用下面的写法<br>
{"Y-m-d"|date:$time} <br>

Smarty函数的使用(使用PHP的内置函数)str_replace -2<br>
<!-- 在php中的使用 str_replace('d','h',$str) -->
{'d'|str_replace:'h':$str} <br>

9、自定义Smarty函数

案例:

	//自定义函数
	function test($params) {
		/*print_r($params);
		exit;*/
		$p1 = $params['p1'];
		$p2 = $params['p2'];
		return '传入的参数1值为'.$p1.',传入的参数2值为'.$p2;
	}

	$smarty->registerPlugin('function', 'f_test', 'test');

这样就可以在视图中使用test函数了,如下:

 

Smarty函数的使用——自定义函数 -3
{f_test p1='abc' p2='edf'} <!-- p1 p2 参数(或者称为属性)会打包成数组发送给f_test函数-->

10、Smarty插件的学习

10.1、什么是Smarty插件:

       Smarty的插件本质上是function函数

10.2、Smarty插件常用类型:

       functions 函数插件

       modifiers  修饰插件

       block functions 区块函数插件

10.3、如何来制作、使用插件:

(1)使用registerPlugin方法注册写好的自定义的函数

(2)将写好的插件放入Smarty解压目录中lib目录下的plugins目录里

(3)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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft