之前的mvc设计模式不论是java版还是php版都会出现在页面调用业务代码的情况,这种情形对代码的维护和分工都很不利,所以就出现了模板引擎,例如velocity,smarty。java里面模板引擎用的很少,php估计比较多。下面我分享下我的第一个模板引擎程序
1.下载开发要用到的smarty
下载地址:http://www.smarty.net/download
要注意的是smarty3的版本需要php5.2以上
2.把下载好的smarty解压并复制libs文件夹到我们的工作空间,并新建templates和templates_c文件夹,templates用来存放模板文件,templates_c存放编译后的东西
3.编写一个模板文件,可以是html,tpl或者其他类型的后缀
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>使用模板</title> </head> <body> #*显示传过来的值*# <h3>#$message#</h3> </body> </html>
4.最后是把smarty和模板联系起来的php,开发中这一部分可能是控制器
<?php require_once "libs/Smarty.class.php"; $smart=new Smarty(); //设置smarty的分隔符,修改默认的{ 防止和css/javascript $smart->left_delimiter="#"; $smart->right_delimiter="#"; //把值交给smarty引擎处理 $smart->assign("message","hello smarty"); //smarty引擎找到相应的模板文件,把值传递过去 $smart->display("index.html"); ?>使用smarty的时候最好设置一下时区,否则会出出现警告或通知。最后来看下运行效果