本文實(shí)例講述了CodeIgniter框架實(shí)現(xiàn)的整合Smarty引擎。分享給大家供大家參考,具體如下:
Smarty的模板機(jī)制很強(qiáng)大,一般情況下CI框架無需整合其他模板標(biāo)簽,因?yàn)镻HP本身就是一種標(biāo)簽,簡(jiǎn)單易用。Codeigniter整合Smarty教程(我用的都是最新版本)如下:
第一步:下載Codeigniter最新版本:CodeIgniter框架源碼
第二步:下載Smarty最新版本:Smarty引擎源碼
第三步:具體配置
我已將本人整合好的代碼上傳,有興趣的可以下載閱讀。Codeigniter框架整合Smarty引擎DEMO 。
1、準(zhǔn)備
將smarty拷貝到application/libraries下,然后再根目錄下下新建templates,templates_c,config,cache目錄,結(jié)構(gòu)如下:
2、修改入口文件
在入口文件index.php中新增:
1
|
define( 'ROOT' , dirname( __FILE__ )); |
3、新建CI_Smarty.php
在libraries文件下新建CI_Smarty.php,寫如下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?php /** * ======================================= * Created by PK Technology. * Author: ZhiHua_W * Date: 2016/10/31 0031 * Time: 上午 9:16 * Project: CI整合 * Power: CI框架整合smarty * ======================================= */ defined( 'BASEPATH' ) OR exit ( 'No direct script access allowed' ); require (APPPATH . 'libraries/smarty/Smarty.class.php' ); class CI_Smarty extends Smarty { public function __construct( $template_dir = '' , $compile_dir = '' , $config_dir = '' , $cache_dir = '' ) { parent::__construct(); if ( is_array ( $template_dir )) { foreach ( $template_dir as $key => $value ) { $this -> $key = $value ; } } else { //ROOT是Codeigniter在入口文件index.php定義的本web應(yīng)用的根目錄 $this ->template_dir = $template_dir ? $template_dir : ROOT . '/templates' ; $this ->compile_dir = $compile_dir ? $compile_dir : ROOT . '/templates_c' ; $this ->config_dir = $config_dir ? $config_dir : ROOT . '/config' ; $this ->cache_dir = $cache_dir ? $cache_dir : ROOT . '/cache' ; } } } |
4、在controller中使用
在控制器Welcome.php中寫入使用方法,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?php defined( 'BASEPATH' ) OR exit ( 'No direct script access allowed' ); class Welcome extends CI_Controller { /** * Welcome constructor. * 寫入構(gòu)造函數(shù),引入CI_Smarty類文件 */ public function __construct() { parent::__construct(); $this ->load->library( 'CI_Smarty' ); } /** * smarty測(cè)試函數(shù) */ public function test() { $this ->ci_smarty->assign( 'test' , 'smarty' ); $this ->ci_smarty->display( 'test.tpl' ); } } |
5、創(chuàng)建模版試圖
在templates文件夾下創(chuàng)建test.tpl文件,寫入如下代碼:
1
2
3
4
5
6
7
8
9
10
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >Codeigniter整合Smarty測(cè)試</ title > </ head > < body > 這是 {$test} 測(cè)試 </ body > </ html > |
6、訪問
至此,我們整合完畢,訪問:http://localhost/Codeigniter_Smarty/index.php/Welcome/test即可看到測(cè)試結(jié)果。
希望本文所述對(duì)大家基于CodeIgniter框架的PHP程序設(shè)計(jì)有所幫助。