2007/02 10
通过component 的形式来使用smarty
前几天也记录了一下将smarty作为cakephp的视图解释器的方法:cakephp与smarty的组合,但是如何使用smarty的缓存却成了问题。因此,把smarty改为组件的形式可能更合适:

To install:
* Download and install Smarty, and place it (preferably) in '/vendors/smarty' (lowercase) directory.
* 建立一些smarty需要的文件夹,与上文同。
* 建立/app/controllers/components/smarty.php文件:

<?php
vendor('Smarty' . DS . 'libs' . DS . 'Smarty.class');
class SmartyComponent extends Smarty
{
        var $controller;
        var $template_dir;
        var $compile_dir;
        var $cache_dir;
        function __construct()
        {
                parent::__construct();
                $this->template_dir = VIEWS;
                $this->compile_dir =  TMP . 'smarty' . DS . 'compile' . DS;
                $this->cache_dir = TMP . 'smarty' . DS . 'cache' . DS;
                $this->left_delimiter = '{#'
                $this->right_delimiter = '#}';
        }
}
?>
 

* That's it!

To use:

Inside your controller:
* 把smarty作为controller的组件(e.g. this->$components = array('smarty');)
* 重构render方法为空,阻止默认view的输出:

function render() { }
 

* 在函数中使用$this->smarty来调用smarty。
* 模板tpl的使用方式与原smarty一样。
示例代码:

class TestsController extends AppController
{
        var $name = 'Tests';
        var $components = array('smarty');
       
        function index()
        {
                $this->smarty->caching = true;
                $this->smarty->cache_lifetime = 3600*5;
                if($this->smarty->is_cached('tests/index.tpl'))
                {
                        $this->smarty->display('tests/index.tpl');
                        exit;
                }
                $this->smarty->assign('posts', $this->Test->findAll());
                $this->smarty->assign('time', date('H:i:s', time()));
                $this->smarty->display('tests/index.tpl');
        }
        function render() { }
}
 


参考: Cake and Smarty
Defined tags for this entry:

Posted by rollenc

1 Trackbacks

  1. rollenc拼博

    cakephp && smarty
    继续使用继续出问题。 我以组件的模式来将cakephp和smarty结合使用,但当我在进行view的设计时又出现问题,由于render已经被重构为空,$html-&gt;input('Post/title', array('size' =&gt; '40'))这样的helper也不能被smarty支持使用了了(我没有找到在smarty中如何支持这些语法的办法),这样就破坏了cakephp中整个的一个MVC结构。这样整进来smarty貌似得不偿失。 看来还得继续研究方法。 cakeph Comments ()

3 Comments

Display comments as(Linear | Threaded)
  1. 学习笔记 says:

    难道现在就没有一个好办法能让cakePHP与smarty整合在一起吗?

    Comments ()

  2. David Shieh says:

    我用了你的方法使Cake和smarty整合在了一起,但是新的问题出现了
    就是我在tpl里无论怎么设置路径,都无法导入js和css文件,不知道你遇到这样的问题了没

    Comments ()

  3. Anonymous says:

    很久不玩cake了
    但是js,css看起来和smarty本身没有太大的关系。
    路径也只是url上的路径,和物理路径没有关系
    应该使用绝对路径就好了
    另外需要检查.htaccess,是不是把所有的url全部转到index.php了。需要修正

    Comments ()

Add Comment


You can use [geshi lang=lang_name [,ln={y|n}]][/lang] tags to embed source code snippets
E-Mail addresses will not be displayed and will only be used for E-Mail notifications