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}