CodeIgniter 預設使用原生 PHP 視圖,若專案需求更強大的模板繼承、快取與修飾器功能,整合 Smarty 是經典選擇。本文詳細說明從下載、封裝類別、自動載入到實際使用的完整流程。
從官網下載 Smarty(如 2.6.20 或 3.x 版),解壓至 CI 的 application/libraries/ 目錄:
application/libraries/Smarty-2.6.20/
Mysmarty.php建立 application/libraries/Mysmarty.php,繼承 Smarty 並整合 CI 資源:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . 'libraries/Smarty-2.6.20/libs/Smarty.class.php';
class Mysmarty extends Smarty {
public function __construct() {
parent::__construct();
$CI = &get_instance();
// 模板與編譯目錄
$this->template_dir = $CI->config->item('smarty_template_dir') ?: APPPATH . 'views/';
$this->compile_dir = $CI->config->item('smarty_compile_dir') ?: APPPATH . 'cache/';
$this->cache_dir = $CI->config->item('smarty_cache_dir') ?: APPPATH . 'cache/';
// 常用全域變數
if (function_exists('site_url')) {
$this->assign('site_url', site_url());
$this->assign('base_url', base_url());
}
// 註冊 CI 物件供模板存取 $this->ci->session->userdata() 等
$this->assign('ci', $CI);
}
/**
* 載入並顯示模板
* @param string $template 模板檔名(不含 .html 會自動補全)
* @param array $data 變數陣列
*/
public function view($template, $data = []) {
if (strpos($template, '.') === false) {
$template .= '.html';
}
if (!empty($data)) {
foreach ($data as $key => $val) {
$this->assign($key, $val);
}
}
$tplPath = $this->template_dir . $template;
if (!is_file($tplPath)) {
show_error("模板不存在: [$template]");
}
$this->display($template);
}
}
編輯 application/config/autoload.php:
$autoload['libraries'] = ['database', 'mysmarty']; // 註意小寫檔名對應類別名
public function index() {
$this->mysmarty->assign('title', '首頁標題');
$this->mysmarty->assign('articles', $this->article_model->get_latest(10));
$this->mysmarty->view('home/index'); // 對應 views/home/index.html
}
CSS、JS、圖片等靜態資源**請勿放入 system/ 或 application/**,應置於網站根目錄:
/assets/css/style.css /assets/js/app.js /assets/images/logo.png
模板中使用 base_url() 產生完整路徑:
<link rel="stylesheet" href="{$base_url}assets/css/style.css">
<img src="{$base_url}assets/images/logo.png" alt="Logo">
{block})、更快的編譯器,建議新專案直接使用 composer require smarty/smarty。$smarty->caching = false,生產環境啟用並設定合理 cache_lifetime。