CodeIgniter 預設視圖文件後綴為 .php,若團隊約定使用 .tpl、.html 或需統一輸出控制(如壓縮、佈局注入),可通過繼承 CI_Controller 重寫 view() 方法實現。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
/**
* 重寫視圖加載
* @param string $file 視圖文件名(不含後綴)
* @param array $data 視圖數據
* @param bool $return true=返回字符串,false=直接輸出
* @return string|void
*/
public function view($file, $data = [], $return = false) {
// 統一追加 .tpl 後綴,避免控制器重複寫後綴
$viewFile = $file . '.tpl';
// 兼容 CI 3/4 寫法:$this->load->view() 返回字符串需第三參數為 true
$output = $this->load->view($viewFile, $data, true);
if ($return) {
return $output;
}
echo $output;
}
}
class Welcome extends MY_Controller {
public function index() {
$this->view('welcome_message', ['title' => 'Hello CI']); // 自動查找 welcome_message.tpl
}
}
$this->config->item('theme') . '/' . $file . '.tpl'。Template Parser 庫實現 {header} 佔位符替換。echo $this->minifyHtml($output); 移除多餘空白字符。$this->cache->save() 實現視圖片段緩存。將視圖加載邏輯集中在基類控制器,不僅統一了團隊規範,更為後續功能擴展預留了擴展點,是 CodeIgniter 專案架構演進的關鍵一步。