CodeIgniter 原生 $this->load->view() 僅支援單一視圖載入。引入 Template 庫後,即可實現「佈局模板 + 內容視圖」的嵌套架構,並支援區塊變數注入、導航高亮、多模板切換等進階功能。
ci_template_library.zip,解壓 Template.php 至 application/libraries/application/config/autoload.php:$autoload['libraries'] = array('template');// 載入 about 視圖並嵌入 template 佈局
$this->template->load('template', 'about', $data);
對應檔案結構:
application/views/template.php:佈局模板application/views/about.php:內容視圖<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<div id="contents"><?= $contents ?></div>
<div id="footer">Copyright 2024</div>
</body>
</html>
$contents 會自動被注入內容視圖渲染結果。
控制器中設定:
$this->template->set('title', 'About Me');
模板中直接使用 <?= $title ?>。
控制器:
$this->template->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));
$this->template->set('nav', 'About'); // 目前頁面
模板:
<ul class="navigation">
<?php foreach($nav_list as $i => $nav_item): ?>
<li class="<?= ($nav == $nav_item ? 'selected' : '') ?>">
<?= anchor($nav_item, $nav_item) ?>
</li>
<?php endforeach ?>
</ul>
需自動載入 url helper:$autoload['helper'] = array('url');
在 libraries/Template.php 擴充自訂方法:
function load_main($view = '', $view_data = array(), $return = FALSE) {
$this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));
$this->load('template', $view, $view_data, $return);
}
控制器調用:
$this->template->set('nav', 'About');
$this->template->set('title', 'About Me');
$this->template->load_main('about');
var $template_data = array();
function set($name, $value) { $this->template_data[$name] = $value; }
function load($template, $view, $view_data, $return) {
$this->CI =& get_instance();
// 先渲染內容視圖為字串
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
// 再渲染佈局模板
return $this->CI->load->view($template, $this->template_data, $return);
}
Template 庫輕量且無侵入性,極適合中小型 CI 專案快速建立可維護的視圖架構。若專案規模較大,建議評估 Blade、Twig 等功能更完整的模板引擎。