封装Smarty模板的配置方法
Smarty模板的配置方法是应用Smaty模板的关键,但是用户不能在每次使用Smarty时都写一遍配置文件。这样不仅使服务器增加了负担,更主要的是使程序的可读性变差,为了解决这个问题笔者决定将Smarty的配置方法封装到一个类中,这样可以在需要应用Smarty模板的地方直接调用类文件即可。在本实例中,通过封装的类文件完成Smarty模板的配置,开发一个简单的实例,运行结果如下所示。
实现步骤如下:
(1)下载和安装Smarty类库,本项目中将使用的Smarty类库文件夹libs存储于本堂课的\zmhh\。
(2)在本堂课\zmhh\文件夹下,创建01\system\Smarty文件夹,新建模板文件夹(templates)、编译文件夹(templates_c)、配置文件夹(configs)和缓存文件夹(cache)。
(3)将Smarty配置方法封装到类中,并存储到system.smarty.inc.php文件中。首先,包含Smarty类文件Smarty.class.php然后,定义SmartyProject类,继承Smarty父类。最后,定义SmartyProject()方法,设置Smarty中模板文件(templates)、编译文件(templates_c)、配置文件(configs)和缓存文件(cache)的存储位置。配置文件system.smarty.inc.php的代码如下:
require("../libs/Smarty.class.php");//调用Smarty文件
class SmartyProject extends Smarty{//定义类,继承Smarty父类
function SmartyProject(){//定义方法,配置Smarty模板
$this ->template_dir = "./";//指定模板文件存储在根目录下
$this->compile_dir = "./system/Smarty/templates_c/";//指定编译文件存储位置
$this->config_dir = "./system/Smarty/configs/";
$this->cache_dir = "./system/Smarty/cache/";
}
}
?>
(4)既然已经将Smaryt的配置方法存储到一个类中,那么就需要对类进行实例化,根据返回的对象名称调用Smarty中的方法,类的实例化操作在\system\system.inc.php文件中完成,其返回对象名为$smarty。代码如下:
require("system.smarty.inc.php");//调用类文件
$smarty=new SmartyProject();//执行类的实例化操作
?>
(5)在\zmhh\01\文件夹下创建index.php文件。首先通过include_once语句包含system\sytstem.inc.php配置文件,对Smarty模板引擎进行配置,然后通过Smarty中的assign方法向模板中传递数据,最后通过display方法指定模板页。代码如下:
include_once("system/system.inc.php");
/*使用Smarty赋值方法将一对名称/方法发送到模板中*/
$smarty->assign('title','走进Smarty模板引擎');
/*显示模板*/
$smarty->display('index.html');
?>
(6)在\zmhh\01\文件夹下新建一个index.html静态页,获取Smarty模板变量传递的数据。代码如下:
ttp://w3.org/1999/xhtml">
{$title}