CodeIgniter集成Smarty


CodeIgniter是一款很優秀的輕量級MVC框架,而Smarty是目前最流行的php模板框架。兩者配合起來使用,加快開發效率。

 

第一步:安裝CodeIgniter

點擊立即下載最新版本的Zip包>>

解壓后,復制文件夾下面的application、system、index.php至項目根目錄中

 

第二步:安裝Smarty

點擊下載最新的Zip包>>

在CodeIgniter的application目錄下的third_party目錄中新建一個名為smarty的目錄,將解壓出來的libs包復制到該目錄中。

 

第三步:創建模板目錄

在application目錄的views目錄中創建兩個文件夾templates、templates_c

 

第四步:編寫安裝代碼

我是從http://www.coolphptools.com/codeigniter-smarty 下載的代碼,但可能版本問題,並不能直接拿來使用,我修改了部分代碼。

Smarty.php(復制至appliction/libraries目錄中)

   1: <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
   2:  
   3: /**
   4:  * Smarty Class
   5:  *
   6:  * @package        CodeIgniter
   7:  * @subpackage    Libraries
   8:  * @category    Smarty
   9:  * @author        Kepler Gelotte
  10:  * @link        http://www.coolphptools.com/codeigniter-smarty
  11:  */
  12: //require_once( BASEPATH.'libs/smarty/libs/Smarty.class.php' );
  13: require_once( APPPATH.'third_party/smarty/libs/Smarty.class.php' );
  14:  
  15: class CI_Smarty extends Smarty {
  16:  
  17:     function CI_Smarty()
  18:     {
  19:         parent::Smarty();
  20:  
  21:         $this->compile_dir = APPPATH . "views/templates_c";
  22:         $this->template_dir = APPPATH . "views/templates";
  23:         $this->assign( 'APPPATH', APPPATH );
  24:         $this->assign( 'BASEPATH', BASEPATH );
  25:  
  26:         log_message('debug', "Smarty Class Initialized");
  27:     }
  28:  
  29:     function __construct()
  30:     {
  31:         parent::__construct();
  32:  
  33:         $this->compile_dir = APPPATH . "views/templates_c";
  34:         $this->template_dir = APPPATH . "views/templates";
  35:         $this->assign( 'APPPATH', APPPATH );
  36:         $this->assign( 'BASEPATH', BASEPATH );
  37:  
  38:         // Assign CodeIgniter object by reference to CI
  39:         if ( method_exists( $this, 'assignByRef') )
  40:         {
  41:             $ci =& get_instance();
  42:             $this->assignByRef("ci", $ci);
  43:         }
  44:  
  45:         log_message('debug', "Smarty Class Initialized");
  46:     }
  47:  
  48:  
  49:     /**
  50:      *  Parse a template using the Smarty engine
  51:      *
  52:      * This is a convenience method that combines assign() and
  53:      * display() into one step. 
  54:      *
  55:      * Values to assign are passed in an associative array of
  56:      * name => value pairs.
  57:      *
  58:      * If the output is to be returned as a string to the caller
  59:      * instead of being output, pass true as the third parameter.
  60:      *
  61:      * @access    public
  62:      * @param    string
  63:      * @param    array
  64:      * @param    bool
  65:      * @return    string
  66:      */
  67:     function view($template, $data = array(), $return = FALSE)
  68:     {
  69:         foreach ($data as $key => $val)
  70:         {
  71:             $this->assign($key, $val);
  72:         }
  73:         
  74:         if ($return == FALSE)
  75:         {
  76:             $CI =& get_instance();
  77:             if (method_exists( $CI->output, 'set_output' ))
  78:             {
  79:                 $CI->output->set_output( $this->fetch($template) );
  80:             }
  81:             else
  82:             {
  83:                 $CI->output->final_output = $this->fetch($template);
  84:             }
  85:             return;
  86:         }
  87:         else
  88:         {
  89:             return $this->fetch($template);
  90:         }
  91:     }
  92: }
  93: // END Smarty Class

 

第五步:更新CodeIgniter配置

關於CodeIgniter的配置,豆瓣上有一篇別人寫的日記。查看詳情>>

這里只是修改application/config/autoload.php文件中的libraries項,讓頁面自動載入smarty。如果不在這里配置,只需在要用到smarty的地方顯示調用$this->load->library(‘smarty’);

 

第六步:運行實例

默認的例子是直接訪問你的域名,比如這里meteoric001.com/

或者使用:

meteoric001.com/index.php/welcome/

meteoric001.com/index.php/welcome

meteoric001.com/index.php/welcome/index

 

關於url的設計,可以參考CodeIgniter的用戶指南 CodeIgniter URL

 

URL里面帶個index.php可能不太好看,這里修改一下服務器配置(nginx為例)

 

最后寫一個名叫example的例子,運行效果

application/controllers/example.php

   1: <?php
   2: class Example extends Controller {
   3:  
   4:     function Example()
   5:     {
   6:         parent::Controller();
   7:  
   8:         // $this->load->helper(array('form', 'url'));
   9:         $this->load->library('form_validation');
  10:         $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
  11:     }
  12:  
  13:     function index()
  14:     {
  15:         // This example is taken from the Smarty demo and modified slightly
  16:         $this->smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill");
  17:         $this->smarty->assign("FirstName",array("John","Mary","James","Henry"));
  18:         $this->smarty->assign("LastName",array("Doe","Smith","Johnson","Case"));
  19:         $this->smarty->assign("Class",array(array("A","B","C","D"), array("E", "F", "G", "H"), array("I", "J", "K", "L"), array("M", "N", "O", "P")));
  20:  
  21:         $this->smarty->assign("contacts", array(array("phone" => "555-1234", "fax" => "555-2345", "cell" => "999-9999"), array("phone" => "555-4444", "fax" => "555-3333", "cell" => "888-8888")));
  22:  
  23:         $this->smarty->assign("state_values", array( 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY' ));
  24:         $this->smarty->assign("state_output", array( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ));
  25:  
  26:         // english is the default if you don't set lang
  27:         $this->smarty->assign("lang", "english");
  28:  
  29:         // Set the validation rules if this is a submit
  30:         if ( $this->input->post('action') == 'submit' )
  31:         {
  32:             $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
  33:             $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
  34:             $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
  35:             $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
  36:             $this->form_validation->set_rules('state', 'State', '');
  37:  
  38:             if ( ! $this->form_validation->run() )
  39:             {
  40:                 $data['error'] = 'Check and fix the form errors below';
  41:             }
  42:             else
  43:             {
  44:                 $data['message'] = 'Thanks for posting!';
  45:             }
  46:         }
  47:  
  48:         // These assignments are passed by the associative array
  49:         $data['title'] = 'Welcome to the Smarty Website';
  50:         $data['bold'] = true;
  51:         $data['ip_address'] = $this->input->server('REMOTE_ADDR');
  52:  
  53:         // Calling the convenience function view() that allows passing data
  54:         $this->smarty->view( 'example.tpl', $data );
  55:     }
  56: }

 

另外一個頁面模板:

 

example的代碼可以從這里下載,需要適當做一些修改。立即下載>>

 

本文參考:

CodeIgniter+Smarty - Perfect Together

CodeIgniter URL


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM