多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 3.5 smarty模板引擎 ### 1. 安装 smarty/smarty 模板引擎 ~~~ composer require smarty/smarty ~~~ 官网:<http://www.smarty.net/docs/zh_CN/> ### 2. 使用模板引擎 *D:\wamp\www\web.com\core\thinkphp.php* 初始化时,实例化模板引擎类 ~~~ public function __construct() { // 模板引擎实例化、设置 $this->smarty = new \Smarty; $this->smarty->setTemplateDir(APP.'/view/'); $this->smarty->setCompileDir(THINKPHP.'/log/view_c'); $this->smarty->setCacheDir(THINKPHP.'/log/cache/'); // $smarty->force_compile = true; // $this->smarty->debugging = true; // $this->smarty->caching = true; $this->smarty->cache_lifetime = 120; } ~~~ 定义的2个方法 ~~~ // 传递数据 public function assign($name, $value) { $this->smarty->assign($name, $value); } // 显示视图 public function display($file) { $this->smarty->display($file); } ~~~ ### 3. 控制器调用模型 *D:\wamp\www\web.com\app\ctrl\indexCtrl.php* ~~~ <?php namespace app\ctrl; use app\model\catModel; class indexCtrl extends \core\thinkphp { public function index() { // 实例化模型 $model = new catModel(); $ret = $model->lists(); $this->assign("cats", $ret); // 传递数据 $this->display('index/index.html'); // 显示视图 } } ~~~ 从数据库获取的数组信息,保存在变量中。 ### 4. 创建模板文件 *D:\wamp\www\web.com\app\view\index\index.html* ~~~ {$cats|dump} ~~~ ![](https://box.kancloud.cn/1487fbe226a5dd1e11b4fa7f3a058859_759x552.png) 模板引擎最大的特点是模板继承等特性。 我们创建一个模板文件:*D:\wamp\www\web.com\app\view\layouts\main.html* ~~~ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>视图文件</title> </head> <body> <header> 头部区域 </header> <div class="content"> <p>内容区域</p> {block name=body}{/block} </div> <footer> 尾部区域 </footer> </body> </html> ~~~ 在视图文件中使用 `foreach` 进行循环遍历显示数据 *D:\wamp\www\web.com\app\view\index\index.html* ~~~ {extends file='layouts/main.html'} {block name=body} <table border="1" width="50%"> {foreach $cats as $i} <tr> <td>{$i['cat_id']}</td> <td>{$i.catname}</td> <td>{$i.num}</td> </tr> {/foreach} </table> {/block} ~~~ ![](https://box.kancloud.cn/39352176e0c69a3707c87aded0c57e31_759x552.png)