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

CodeIgniter 整合 Smarty 模板引擎完整配置教學

     編輯:PHP 相關知識

CodeIgniter + Smarty 3.x 整合指南:從安裝到測試完整流程

Smarty 作為成熟的 PHP 模板引擎,提供模板繼承、緩存、插件機制等強大功能。本文詳述在 CodeIgniter 3.x 中整合 Smarty 3.1+ 的標準化步驟。

安裝與目錄佈署

  1. 下載 Smarty 3.1.8+ (或最新版),解壓取得 libs/ 目錄
  2. 重命名 libs 為 Smarty,複製至 application/libraries/Smarty/
  3. 建立編譯目錄 application/templates_c/,設定寫入權限 chmod 777

建立 CI 專用載入類別

application/libraries/Template.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . 'libraries/Smarty/Smarty.class.php';

class Template extends Smarty {
    public function __construct() {
        parent::__construct();
        
        // 目錄配置
        $this->setTemplateDir(APPPATH . 'views/');
        $this->setCompileDir(APPPATH . 'templates_c/');
        $this->setCacheDir(APPPATH . 'cache/smarty/');
        $this->setConfigDir(APPPATH . 'config/smarty/');
        
        // 分隔符 (避免與 CI/JS 衝突)
        $this->left_delimiter  = '<{';
        $this->right_delimiter = '}>';
        
        // 開發環境設定
        if (ENVIRONMENT === 'development') {
            $this->force_compile = true;
            $this->caching = false;
            $this->debugging = true;
        } else {
            $this->caching = true;
            $this->cache_lifetime = 3600;
        }
        
        // 註冊 CI 專用函數
        $this->registerPlugin('function', 'site_url', [$this, '_site_url']);
        $this->registerPlugin('function', 'base_url', [$this, '_base_url']);
        $this->registerPlugin('modifier', 'esc', 'html_escape');
    }
    
    // 模板函數:site_url()
    public function _site_url($params, $template) {
        $ci =& get_instance();
        return $ci->config->site_url($params['url'] ?? '');
    }
    
    // 模板函數:base_url()
    public function _base_url($params, $template) {
        $ci =& get_instance();
        return $ci->config->base_url($params['url'] ?? '');
    }
    
    // 便捷顯示方法
    public function show($tpl, $data = []) {
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }
        $this->display($tpl);
    }
}

自動載入配置

application/config/autoload.php

$autoload['libraries'] = ['database', 'session', 'template']; // 'template' 對應 Template.php

控制器使用範例

class Welcome extends CI_Controller {
    public function index() {
        $this->template->assign('title', 'Smarty 整合測試');
        $this->template->assign('user', [
            'name' => '張三',
            'roles' => ['admin', 'editor']
        ]);
        $this->template->assign('items', ['蘋果', '香蕉', '橘子']);
        
        // 直接顯示
        $this->template->show('welcome.tpl');
        
        // 或分步指派
        // $this->template->display('welcome.tpl');
    }
}

Smarty 模板檔案

application/views/welcome.tpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title><{$title}></title>
    <link href="<{base_url url='assets/css/app.css'}>" rel="stylesheet">
</head>
<body>
    <h1>歡迎, <{$user.name|esc}>!</h1>
    
    <p>角色: <{$user.roles|@join:', '}></p>
    
    <ul>
    <{foreach $items as $item}>
        <li><{$item|esc}></li>
    <{/foreach}>
    </ul>
    
    <{if $user.roles|in_array:'admin'}>
        <a href="<{site_url url='admin/dashboard'}>">管理後台</a>
    <{/if>}
</body>
</html>

進階功能:模板繼承 (Smarty 3+)

application/views/layouts/main.tpl

<!DOCTYPE html>
<html>
<head>
    <title><{block name='title'}>預設標題<{/block}></title>
    <{block name='head'}><{/block}>
</head>
<body>
    <header><{block name='header'}>共用導航<{/block}></header>
    <main><{block name='content'}><{/block}></main>
    <footer><{block name='footer'}>版權所有<{/block}></footer>
    <{block name='scripts'}><{/block}>
</body>
</html>

application/views/page/home.tpl

<{extends file='layouts/main.tpl'}>

<{block name='title'}>首頁 - 我的網站<{/block}>

<{block name='content'}>
    <h1>歡迎來到首頁</h1>
    <p><{$intro_text}></p>
<{/block}>

<{block name='scripts'}>
    <script src="<{base_url url='js/home.js'}>"></script>
<{/block}>

效能優化建議

  • 生產環境啟用 caching = true,設定合理 cache_lifetime
  • 使用 {nocache}{/nocache} 包裹動態區塊 (如用戶資訊、購物車)
  • 模板編譯目錄放置於 SSD 或 tmpfs 提升 I/O
  • 大型專案考慮將常用模板函數編譯為 PHP 擴展

常見問題排查

現象原因解決
空白頁面編譯目錄無寫入權限chmod 777 templates_c/
變數不顯示分隔符衝突或 assign 鍵名錯誤檢查 left/right_delimiter、assign 參數
模板修改不生效快取未清除刪除 templates_c/ 內容或設定 force_compile
函數未定義registerPlugin 名稱錯誤檢查 Template.php 註冊名稱與模板呼叫一致

完成整合後,您將擁有強大的模板繼承、緩存、插件擴展能力,同時保持 CodeIgniter 輕量核心優勢,實現關注點完美分離。

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