自己动手写个小框架之四

     框架使用了smarty模板引擎,由libs和tpls两个文件夹及内容组成。在libs中我们可以看到Smarty.class.php文件,它是smarty的核心文件。我们要做的是加载它,然后声明一个smarty对象,进行一些基本的设置。在kernel中,由baseController.php对其进行封装。

 1 <?php
 2 
 3 class Controller {
 4 
 5     private $Tpl;
 6 
 7     public function __construct() {
 8         $path = $_SERVER['DOCUMENT_ROOT'] . '/dluf/';
 9         include $path . "/libs/Smarty.class.php";
10         $tpl = new Smarty();
11         $tpl->template_dir = $path . "/tpls/templates/";
12         $tpl->compile_dir = $path . "/tpls/templates_c/";
13         $tpl->config_dir = $path . "/tpls/configs/";
14         $tpl->cache_dir = $path . "/tpls/cache/";
15         $tpl->caching = false;
16         $tpl->cache_lifetime = 300;
17         $tpl->left_delimiter = '<{';
18         $tpl->right_delimiter = '}>';
19         $this->Tpl = $tpl;
20     }
21 
22     public function render($template, $parmarr) {
23         foreach ($parmarr as $key => $value) {
24             $this->Tpl->assign($key, $value);
25         }
26         $this->Tpl->display($template);
27     }
28 
29 }
30 
31 ?>

声明smarty对象和赋值:
9
include $path . "/libs/Smarty.class.php"; //加载核心类 10 $tpl = new Smarty(); 11 $tpl->template_dir = $path . "/tpls/templates/"; 12 $tpl->compile_dir = $path . "/tpls/templates_c/"; 13 $tpl->config_dir = $path . "/tpls/configs/"; 14 $tpl->cache_dir = $path . "/tpls/cache/"; 15 $tpl->caching = true; 16 $tpl->cache_lifetime = 300; 17 $tpl->left_delimiter = '<{'; 18 $tpl->right_delimiter = '}>'; 19 $this->Tpl = $tpl;
template_dir 存放模板文件;
compile_dir  存放模板引擎编译后生产文件;
config_dir   存放模板页使用的配置文件;
cache_dir    存放模板引擎生产的缓存文件;
caching      false关闭,true开启;
cache_lifetime 缓存时间,以秒为单位;

(调试时应关闭caching,可较快看到调试结果;对于数据更新较快,可以设置cache_lifetime小一些。)
left_delimiter 模板标签开始标志;
right_delimiter 模板标签结束标志。


为相应tpl模板页面绑定数据:
22     public function render($template, $parmarr) {
23         foreach ($parmarr as $key => $value) {
24             $this->Tpl->assign($key, $value);
25         }
26         $this->Tpl->display($template);
27     }
$this->Tpl->assign($key, $value) 赋值;
$this->Tpl->display($template)   页面显示。

系列五中将会介绍tpl模板文件,并使用smarty官方的例子。

posted on 2013-04-26 18:53  d&lufd  阅读(248)  评论(0编辑  收藏  举报

导航