---
title: "Yii整合smarty"
author: "yd514"
date: "2013-08-30T16:13:01Z"
tags: []
categories: ["Web前端"]
slug: "yii-smarty"
draft: false
lastmod: "2013-08-30T16:13:01Z"
id: 1934065
url: "https://yd514.iteye.com/blog/1934065"
---

在protected下的extensions文件夹放入我们的smarty类包，按照约定我们同在protected下的extensions(Yii的扩展默认都扔到这里)中建立CSmarty类文件。

内容如下:

01. &lt;?php
02. /\**
03. \*Author:Elite
04. \*/
05. require\_once(Yii::getPathOfAlias('application.extensions.smarty').DIRECTORY\_SEPARATOR.'Smarty.class.php');
06. define('SMARTY\_VIEW\_DIR', Yii::getPathOfAlias('application.views'));
07. class CSmarty extends Smarty {
08. const DIR\_SEP = DIRECTORY\_SEPARATOR;
09. function \_\_construct() {
10. parent::\_\_construct();
11. $this-&gt;template\_dir = SMARTY\_VIEW\_DIR;
12. $this-&gt;compile\_dir = SMARTY\_VIEW\_DIR.self::DIR\_SEP.'template\_c';
13. $this-&gt;caching = true;
14. $this-&gt;cache\_dir = SMARTY\_VIEW\_DIR.self::DIR\_SEP.'cache';
15. $this-&gt;left\_delimiter  =  '&lt;!--{';
16. $this-&gt;right\_delimiter =  '}--&gt;';
17. $this-&gt;cache\_lifetime = 3600;
18. }
19. function init() {}
20. }
21. ?&gt;

 

然后建立相关联的文件夹。

 

紧接这是我们的配置部分

打开protected/config/main.php

在components数组中加入

'smarty'=&gt;array(  
    'class'=&gt;'application.extensions.CSmarty',  
),

最后在action中直接用Yii::app()-&gt;smarty就可以试用smarty了。如果每次在action中使用Yii::app()-&gt;smarty比较麻烦的话，可以在components下的Controller中可以加入

protected $smarty = '';

protected function init() {  
       $this-&gt;smarty = Yii::app()-&gt;smarty;  
 }

然后在action中直接可以用$this-&gt;smarty使用smarty了。

本文出自 “[我相信](http://mrcelite.blog.51cto.com/)” 博客，请务必保留此出处[http://mrcelite.blog.51cto.com/2977858/789406](http://mrcelite.blog.51cto.com/2977858/789406)