ThinkPHP (3.x) 內建模板引擎,但支援第三方引擎插件。Smarty 作為成熟模板引擎,提供繼承、緩存、插件等優勢。本文詳細說明:官方插件安裝、自定義插件繞過核心 View 類限制、配置雙引擎共存、變量賦值與渲染差異、常見坑點。
libs/ 目錄複製至 ThinkPHP/Extend/Library/Template/Smarty/ (或項目 Extend/Library/Template/Smarty/)。Conf/config.php:
'THINK_PLUGIN_ON' => true, 'TMPL_ENGINE_TYPE' => 'Smarty', // 不區分大小寫
Tpl/ 目錄,副檔名 .html 或 .tpl。$this->display()。缺點:核心 View::fetch() 仍會執行 ThinkPHP 內建模板的編譯/快取邏輯,影響效能。
修改 ThinkPHP/Lib/Core/View.class.php (或項目覆蓋) 中的 getInstance() 與 __construct(),改為 init() 延遲初始化,並在項目 Extend/Library/Template/TpSmarty.class.php 實現精簡 Smarty 封裝。
// ThinkPHP/Lib/Core/View.class.php (或項目 Lib/Core/View.class.php)
static public function getInstance() {
return get_instance_of(__CLASS__, 'init'); // 呼叫 init 而非 __construct
}
public function init($type = '') {
if (empty($type)) $type = strtoupper(C('TMPL_ENGINE_TYPE'));
if (in_array($type, ['PHP', 'THINK'])) {
// 原生邏輯...
} else {
// 第三方引擎:直接實例化對應類
$class = $type; // 如 'TpSmarty'
vendor($class); // 載入 Extend/Library/Template/TpSmarty.class.php
return new $class();
}
}
// Extend/Library/Template/TpSmarty.class.php
class TpSmarty extends Smarty {
public function __construct() {
parent::__construct();
$this->caching = true;
$this->template_dir = TMPL_PATH; // 項目模板目錄
$this->compile_dir = CACHE_PATH; // 編譯目錄
$this->cache_dir = TEMP_PATH; // 緩存目錄
// 可依項目調整 left/right_delimiter
}
// 兼容 ThinkPHP display/fetch 介面
public function display($template = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
if (empty($template)) $template = $this->getTemplateName(); // 需自行實現邏輯
parent::display($template);
}
public function fetch($template = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
if (empty($template)) $template = $this->getTemplateName();
return parent::fetch($template);
}
}
// Conf/config.php 'THINK_PLUGIN_ON' => true, 'TMPL_ENGINE_TYPE' => 'TpSmarty',
class IndexAction extends Action {
public function index() {
$this->assign('test', 'testss');
$this->display('default/index.html'); // 必須指定完整路徑
}
}
TMPL_ENGINE_TYPE 改回 Think。Tpl/default/Index/index.html 建立模板。$this->display(); (自動推導)。| 特性 | ThinkPHP 內建 | Smarty (插件) |
|---|---|---|
| 模板語法 | {$var}, {volist}, {if} | {$var}, {foreach}, {if}, {block} 繼承 |
| 模板繼承 | 不支援 | 支援 {extends}/{block} |
| 編譯緩存 | Runtime/Cache/ | Smarty compile_dir/cache_dir |
| display 參數 | 可為空 (自動推導) | 建議指定完整路徑 |
| 變量賦值 | $this->assign() | 相同 |
| 插件擴展 | 標簽庫 | Smarty Plugins (modifier, function, block) |
TMPL_ENGINE_TYPE 拼寫、vendor() 載入路徑、類名大小寫。display() 需指定模板名,ThinkPHP 自動推導邏輯在插件中需自行實現 getTemplateName()。templates_c/ 下編譯文件、或設定 $smarty->force_compile = true (開發)。$charset 參數正確。ThinkPHP 模板引擎插件機制極具彈性。**官方插件**適合快速接入,**自定義插件**可繞過核心 View 類的冗餘邏輯,發揮 Smarty 最大效能。掌握 View::getInstance() 工廠模式、vendor() 自動載入、TMPL_ENGINE_TYPE 切換、模板目錄映射、雙引擎共存驗證,即能在遷移、重構、多模板需求中游刃有餘。ThinkPHP 5/6 已內建更強大的模板引擎 (支援佈局、繼承),新專案建議直接使用內建或遷移至 Laravel Blade/Twig。