首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CodeIgniter 整合 Smarty 模板引擎完整步驟教學

     編輯:PHP 相關知識

CodeIgniter 整合 Smarty 模板引擎完整步驟教學

本文詳細說明如何在 CodeIgniter 中整合 Smarty 模板引擎。

1. 下載 Smarty

解壓至 CI 的 libraries 目錄,例如:ci/application/libraries/Smarty-2.6.20

2. 撰寫 Mysmarty.php 類別庫

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require "Smarty-2.6.20/libs/Smarty.class.php";

class Mysmarty extends Smarty {
    function Mysmarty() {
        $this->Smarty();
        $config =& get_config();
        // 絕對路徑避免「template not found」錯誤
        $this->template_dir = (!empty($config['smarty_template_dir']) ? $config['smarty_template_dir'] : BASEPATH . 'application/views/');
        $this->compile_dir = (!empty($config['smarty_compile_dir']) ? $config['smarty_compile_dir'] : BASEPATH . 'cache/');
        // 使用 CI 的快取資料夾
        if (function_exists('site_url')) {
            $this->assign("site_url", site_url());
        }
    }

    function view($resource_name, $params = array()) {
        if (strpos($resource_name, '.') === false) {
            $resource_name .= '.html';
        }
        if (is_array($params) && count($params)) {
            foreach ($params as $key => $value) {
                $this->assign($key, $value);
            }
        }
        // 檢查模板檔案是否存在
        if (!is_file($this->template_dir . $resource_name)) {
            show_error("template: [$resource_name] cannot be found.");
        }
        return parent::display($resource_name);
    }
}
?>

3. 自動載入或手動載入

在 autoload.php 設定:

$autoload['libraries'] = array('database', 'mysmarty');

或於需要時手動載入:$this->load->library("mysmarty");

4. 變數指派與顯示模板

$this->mysmarty->assign('test', 'Hello World.');
$this->mysmarty->view('smarty');

注意: 圖片、CSS 等外部資源檔案請放在 CI 系統資料夾外的網站根目錄下,建議使用 base_url() 存取,例如 base_url()."images/xxx.jpg",切勿放入 system 目錄。

補充工具推薦:

更多 CodeIgniter 相關內容請參考本站專題:《CodeIgniter 入門教程》、《CI(CodeIgniter) 框架進階教程》、《PHP 優秀開發框架總結》、《ThinkPHP 入門教程》、《ThinkPHP 常用方法總結》、《Zend Framework 框架入門教程》、《PHP 面向物件程式設計入門教程》、《PHP+MySQL 資料庫操作入門教程》及《PHP 常見資料庫操作技巧匯總》。

希望本文能對您基於 CodeIgniter 框架的 PHP 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved