smarty模板引擎

Smarty是PHP的模板引擎,用于实现MVC架构中的视图部分,促进逻辑与显示的分离。它减少了代码量,提升了速度,并便于维护。在安装过程中要注意Include/require_once的使用,区分大小写,并理解include与require的区别。Smarty中变量的来源包括assign函数分配、保留变量和配置变量,可以用于展示数据库内容,如通过foreach循环在前端展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

smarty是PHP的一个引擎模板,可以进行更好的进行逻辑与显示的分离,即我们常说的MVC,这个引擎的作用就是将C分离出来。其中的MVC分别指的是M——模型(moder),V——视图(view),C——控制器(controller)。简单来说就是将html代码与php代码分离开,使速度更快,减少代码量,方便程序的修改与维护。

在smarty安装时,涉及到:

Include/include_once

Require/require_once

<?php

//include, include_once, require, require_once
include './smarty-3.1.30/libs/Smarty.class.php';

?>

其中大小写要严格,因为在windows系统下,目录或文件名等不区分大小写,但是在linux系统下,则区分大小写。

include和require都是把一个页面引入到当前页面,但是两者之间也是有区别的,include如果引入的文件不存在,试图继续往下执行,报一个warning(警告错误),而require如果引入的文件不存在,报fatal  error(严重致命错误),不再继续执行。

_once会自动判断文件是否已经引入,如果引入,不再重复执行。

有的文件不允许被包含多次,可以用_once来控制,但是如果从文件的设计上比较规范,能保证肯定不会出现多次包含的错误,这种情况下,建议用include,因为include_once要检测之前有没有包含,效率没有include高。

举个例子:

assign.php(后端):

<?php

//include, include_once, require, require_once
include './smarty-3.1.30/libs/Smarty.class.php';

//定义smarty所使用的文件目录
define('SMARTY_ROOT', './');
//实例化smarty对象(smarty 面对对象)
$smarty = new Smarty();
//指定模板文件所在路径
$smarty->template_dir = SMARTY_ROOT . '/template';

//指定模板编译后的文件所在路径
$smarty->compile_dir = SMARTY_ROOT . '/template_c';

//向模板传递变量(键 值配对)
$smarty -> assign('name','张三');

//指定模板文件显示
$smarty -> display('index.tpl');

?>

assign.tpl(前端):

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<h3>{$name}</h3>
</body>
</html>

assign()函数传递变量。

变量的来源有如下三种:

1.通过PHP程序中的assign函数分配过来。

2.保留变量。

3.配置变量。

其中保留变量和配置变量无需在php中分配(配置变量需要在配置文件中配置)直接在模板中使用。

再例如说,连接数据库将数据库中的内容显示在网页中,代码如下:

demo.php(后端):

<?php

include 'smarty_config.php';

$conn = @new mysqli('localhost','root','','myschool');
if($conn -> connect_error){
	die('连接数据库失败');
}
$conn -> set_charset('utf8');
$sql = "select id,no,name from student1 limit 100";
$ret = $conn -> query($sql);

$data =array();
while($row = $ret -> fetch_assoc()){
	$data[] = $row;
}
$conn -> close();
// print_r($data);
// exit;

$smarty -> assign('title','个人信息');
$smarty -> assign('data',$data);

$smarty -> display('demo.tpl');

?>

demo.tpl(前端):

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{$title}</title>
</head>
<body>
	<table border="1" >
		<tr>
			<td>ID</td>
			<td>学号</td>
			<td>姓名</td>
		</tr>
		{foreach $data as $row}
		<tr>
			<td>{$row.id}</td>
			<td>{$row.no}</td>
			<td>{$row.name}</td>

		</tr>
		{/foreach}
	</table>
</body>
</html>

也可有foreach循环,需要成对出现。

{foreach}

{/foreach}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值