一、概述
Smarty是一个使用PHP写出来的模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。
二、配置
0、从官方网站http://www.smarty.net/download 下载Smarty
1、解压下载的Smarty压缩包,将其中的libs文件夹拷贝到网站目录下,重命名为你想要自定义的名字。如:本例将libs文件夹拷贝到learn文件夹下,将libs重命名为“smarty”。
2、在learn文件夹下新建配置文件smarty.ini.php,代码如下:
<?php
require_once ("smarty/Smarty.class.php"); //加载smarty类库文件
$smarty = new Smarty(); //建立smarty实例对象$smarty
$smarty->config_dir = "./config"; //配置文件目录
$smarty->caching = false; //是否使用缓存,项目在调试期间,不建议启用缓存
$smarty->template_dir = "./templates"; //设置模板目录
$smarty->compile_dir = "./templates_c"; //设置编译目录
$smarty->cache_dir = "./smarty_cache"; //缓存文件夹
//左右边界符,默认为{},但实际应用当中容易与JavaScript相冲突
$smarty->left_delimiter = "{";
$smarty->right_delimiter = "}";
//使用Smarty的testInstall()内置方法测试配置是否成功
//$smarty->testInstall();
?>
3、在对应的位置分别新建配置文件中相应的文件夹config、templates、templates_c、smarty_cache。
4、使用Smarty的testInstall()内置方法可以检测配置是否成功
三、应用示例
learn/index.php代码:
<?php
header("Content-type: text/html; charset=utf-8");
require_once("smarty.ini.php");
$smarty -> assign("welcome","hello smarty!");
$smarty -> display("index.htm");
?>
learn/templates/index.htm代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HELLO SMARTY</title>
</head>
<body>
初识Smarty,应用示例:{$welcome}
</body>
</html>