天天看點

yii2 smarty php,yii架構整合Smarty

必須說明的是,本教程裡所有的YII架構開發網站項目是整合Smarty來開發的,Smarty作為最成熟使用最多的模闆之一,相信大家都比較熟悉。如果還有的同學不是很熟悉,可以參考Smarty教程。不過就算不會也不要緊,我這裡盡量詳細說明讓大家明白。

可以先了解smarty中的assign(),include,display()這幾個函數的用法。另外,還需要知道if-else,foreach這兩個标簽。足矣!

我們先來看一下整個開發目錄檔案:

yii2 smarty php,yii架構整合Smarty

簡單說明一下幾個目錄的作用(存放檔案的内容):

1、framework: YII架構檔案目錄

2、static: 靜态檔案

3、protected: 開發程式檔案目錄

4、uploadfile: 上傳的檔案

配置Smarty支援

1、建立一個類,檔案名為:CSmarty.php内容如下:

require_once (Yii::getPathOfAlias('application.extensions.smarty') . DIRECTORY_SEPARATOR . 'Smarty.class.php');

define('SMARTY_VIEW_DIR', Yii::getPathOfAlias('application.views'));

class CSmarty extends Smarty {

const DIR_SEP = DIRECTORY_SEPARATOR;

function __construct() {

parent::__construct();

$this -> template_dir = SMARTY_VIEW_DIR;

$this -> compile_dir = SMARTY_VIEW_DIR . self::DIR_SEP . 'template_c';

$this -> caching = true;

$this -> cache_dir = SMARTY_VIEW_DIR . self::DIR_SEP . 'cache';

$this -> left_delimiter = '';

$this -> cache_lifetime = 0;

// -- 初始全局資料

$this -> assign('base_url', 'http://www.ttall.net');

$this -> assign('index_url', 'http://www.ttall.net/index.php');

}

function init() {

}

}

把上述類放到檔案目錄:protected/extensions/

2、配置protected/config/main.php

在該檔案中加入如下代碼:

// uncomment the following to define a path alias

// Yii::setPathOfAlias('local','path/to/local-folder');

return array(

'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',

'name'=>'易百IT教程網-www.yiibai.com',

// preloading 'log' component

'preload'=>array('log'),

// autoloading model and component classes

'import'=>array(

'application.models.*',

'application.components.*',

'application.extensions.*',

'application.extensions.smarty.sysplugins.*',

),

// application components

'components'=>array(

'user'=>array(

// enable cookie-based authentication

'allowAutoLogin'=>true,

),

'smarty'=>array(

'class'=>'application.extensions.CSmarty',

),

3、找到檔案protected/components/Controller.php,加入兩個方法:

public function assign($key, $value) {

Yii::app() -> smarty -> assign($key, $value);

}

public function display($view) {

Yii::app() -> smarty -> display($view);

}

這樣,我們就可以在每一個控制器裡直接調用這兩個Smarty方法了。