使用智能模板的示例分析
本文说明了如何使用smarty模板。分享给大家参考,如下:
以smarty3为例
首先在官网下载smarty3模板文件,然后解压。
在解压缩的文件夹中,libs是smarty模板的核心文件,demo包含示例程序。
我们将libs文件夹复制到工作目录中,并将其重命名为smarty。
假设我们在控制器目录下的index.php中使用smarty模板。
index.php
?“phprequire”./smarty/smarty . class . PHP ';$smarty=新Smarty;$ smarty-debug=false;//打开调试模式$ smarty-cache=true;//Open cache $ smarty-cache _ lifetime=120;//缓存时间$ smarty-left _ delimiter=“{”;//左分隔符$ smarty-right _ delimiter=“}”;//右分隔符$ smarty-template _ dir=_ _ dir _ _。'/./view/';//查看目录$ smarty-compile _ dir=_ _ dir _ _。'/./smarty/compile/';//编译目录$ smarty-config _ dir=_ _ dir _ _。'/./smarty/configs/';//配置目录$ smarty-cache _ dir=_ _ dir _ _。'/./smarty/cache/';//缓存目录$list=范围(' A ',' D ');$smarty-assign('list ',$ list);$smarty-assign('name ','赵哲');$ smarty-display(' index . html ');模板文件index.html
html head title/title/head body ph1 { $ name }/h1/p { foreach $ listas $ k=$ v } ph1 { $ k } : { $ v }/h1/p {/foreach }/body/html上述方法的优点是使用起来相对简单,缺点也很明显。
有两种解决方案:
将smarty模板的配置信息写入一个文件,然后其他页面可以通过包含该文件来使用smarty对象。
要求./smarty/smarty . class . PHP ';$smarty=新Smarty;$ smarty-debug=false;//打开调试模式$ smarty-cache=true;//Open cache $ smarty-cache _ lifetime=120;//缓存时间$ smarty-left _ delimiter=“{”;//左分隔符$ smarty-right _ delimiter=“}”;//右分隔符$ smarty-template _ dir=_ _ dir _ _。'/./view/';//查看目录$ smarty-compile _ dir=_ _ dir _ _。'/./smarty/compile/';//编译目录$ smarty-config _ dir=_ _ dir _ _。'/./smarty/configs/';//配置目录$ smarty-cache _ dir=_ _ dir _ _。'/./smarty/cache/';//缓存目录我们自己写一个类,从Smarty类继承,然后把配置信息写在构造函数中。
我们编写了我的马蒂类
?“phprequire”./smarty/smarty . class . PHP ';类mySmarty扩展了Smarty { public function _ _ construct(array $ options=array()){ parent : _ _ construct($ options);$ this-调试=false//打开调试模式$ this-cache=true;//Open cache $ this-cache _ lifetime=120;//缓存时间$ this-left _ delimiter=“{”;//左分隔符$ this-right _ delimiter=“}”;//右分隔符$ this-settemplatedir(_ dir _ _)。'/./view/');//查看目录$ this-setcompiledir(_ dir _ _)。'/./smarty/compile/');//编译目录$ this-set config dir(_ dir _ _)。'/./smarty/configs/');//配置目录$ this-set cached(_ dir _ _)。'/./smarty/cache/');//缓存目录}}此时,控制器中的index.php代码可以优化如下:
?phprequire ' mySmarty.php$ smarty=new mySmarty$list=范围(' A ',' D ');$smarty-assign('list ',$ list);$smarty-assign('name ','赵哲');$ smarty-display(' index . html ');最后,发送福利:smarty3 chm官方文件。
更多对Smarty相关内容感兴趣的读者可以查看本网站专题:《smarty模板入门基础教程》、《PHP模板技术总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》、《php常见数据库操作技巧汇总》。
希望本文对基于smarty模板的PHP编程有所帮助。
版权声明:使用智能模板的示例分析是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。