本文詳細說明如何在 CodeIgniter 中整合 Smarty 模板引擎。
解壓至 CI 的 libraries 目錄,例如:ci/application/libraries/Smarty-2.6.20
<?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);
}
}
?>
在 autoload.php 設定:
$autoload['libraries'] = array('database', 'mysmarty');
或於需要時手動載入:$this->load->library("mysmarty");
$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 程式設計有所幫助。