2012/12/17

CodeIgniter + Smarty

用 Smarty 用了這麼多年,寫 PHP 不用它還真不習慣。以下是 CodeIgniter 整合 Smarty 的步驟:

Step 1. 下載最新的 CodeIgniter 和 Smarty(目前是 CodeIgniter_2.1.3.zip 和 Smarty-3.1.12.tar.gz)。

Step 2. 解壓縮 CodeIgniter_2.1.3.zip
unzip CodeIgniter_2.1.3.zip
Step 3. 把 Smarty-3.1.12.tar.gz 解壓縮,放到 application/third_party/ 目錄下
tar zxvf Smarty-3.1.12.tar.gz -C CodeIgniter_2.1.3/application/third_party/
Step 4. 修改 application/config/constants.php,設定 SMART_DIR 常數
/*
|--------------------------------------------------------------------------
| Smarty Directory
|--------------------------------------------------------------------------
*/
define('SMARTY_DIR', APPPATH . 'third_party/Smarty-3.1.12/libs/');
Step 5. 在 application/libraries/ 目錄下,加入 MySmarty.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MySmarty {
 private static $SMARTY = null;
 
 /**
  * Smarty Singleton
  */
 static function smarty()
 {
  if (null === self::$SMARTY) {
   require_once SMARTY_DIR . 'Smarty.class.php';
   
   $smarty = new Smarty();
   
   // 設定 Smarty 參數
   $smarty->left_delimiter = '{{';
   $smarty->right_delimiter = '}}';

   $smarty->setTemplateDir(APPPATH . 'views');
   $smarty->setCompileDir(APPPATH . 'views/templates_c');
   $smarty->setCacheDir(APPPATH . 'views/cache');
   $smarty->setConfigDir(APPPATH . 'views/config');
   $smarty->compile_check = true;
   $smarty->force_compile = true;
   $smarty->caching = true;
   $smarty->cache_lifetime = 86400;

   if(! file_exists($smarty->compile_dir)) {
    mkdir($smarty->compile_dir, 0777, true);
   }
   if(! file_exists($smarty->cache_dir)) {
    mkdir($smarty->cache_dir, 0777, true);
   }
   
   self::$SMARTY = $smarty;
  }
  return self::$SMARTY;
 }
}
Step 6. 在 application/views 目錄下,建立 Smarty 所需目錄
mkdir CodeIgniter_2.1.3/application/views/config
mkdir -m 777 CodeIgniter_2.1.3/application/views/cache
mkdir -m 777 CodeIgniter_2.1.3/application/views/templates_c
Step 7. 在 controller 裡的使用方式
$this->load->Library('MySmarty');
$smarty = MySmarty::smarty();

$smarty->assign(array("aa"=>"aaa"));
$smarty->display("aaa.tpl");

沒有留言:

張貼留言