Smarty 預設需在 PHP 端 assign() 變數才能在模板使用。透過擴充編譯器,新增 {load} 標籤,讓模板直接聲明式載入資料,類似 {foreach} 語法。
_compile_tag() 中註冊標籤// 在 switch ($tag_name) 中新增:
case 'load':
$this->_push_tag('load');
return $this->_compile_load_start($tag_args);
break;
case '/load':
$this->_pop_tag('load');
// 複用 foreach 結束邏輯
return "";
break;
_compile_load_start()/**
* 編譯 {load} 開始標籤
* 語法:{load table="table_name" where="condition" limit=10 item=rec}
*/
function _compile_load_start($tag_args) {
// 根據參數生成唯一變數名,避免衝突
$key = substr(md5($tag_args), 8, 16);
// 解析屬性:table, where, limit, class, item, key...
$attrs = $this->_parse_attrs($tag_args);
// 預設 CRUD 類別
$class = (!empty($attrs['class'])) ? $attrs['class'] : 'cls_crud';
// 必填:table
if (empty($attrs['table'])) {
trigger_error('{load} 標籤缺少必要屬性 `table`', E_USER_ERROR);
}
// 實例化資料物件並查詢
$db = $class::factory(['table' => $attrs['table']]);
$where = isset($attrs['where']) ? $attrs['where'] : '';
$limit = isset($attrs['limit']) ? (int)$attrs['limit'] : 10;
// 將查詢結果存入模板變數(編譯期執行!)
$this->_tpl_vars[$key] = $db->get_block_list([$where], $limit);
// 轉換為 foreach 語法:{foreach from=$key item=rec}
$foreach_args = "from=\$" . $key . " " . $tag_args;
return $this->_compile_foreach_start($foreach_args);
}
{* 載入測試表前 10 筆 id<100 的資料 *}
{load table="test" where="`id` < 100" limit=10 item=rec}
<div>{$rec.name} - {$rec.email}</div>
{/load}
{* 進階:指定類別、自訂鍵名 *}
{load class="UserModel" table="users" where="status=1" limit=20 item=user key=id}
<option value="{$id}">{$user.username}</option>
{/load}
<?php
// 編譯期執行查詢
$_tmp_abc123 = cls_crud::factory(['table'=>'test'])->get_block_list(['`id`<100'], 10);
?>
<?php $_from = $_tmp_abc123; if (!empty($_from)): foreach ($_from as $key => $rec): ?>
<div><?php echo $rec['name']; ?> - <?php echo $rec['email']; ?></div>
<?php endforeach; endif; unset($_from); ?>
| 優點 | 缺點/風險 |
|---|---|
| 模板自包含,減少控制器樣板代碼 | 編譯期執行查詢,部署/編譯階段需連資料庫 |
| 區塊化資料載入,利於版面複用 | 難以單元測試模板邏輯 |
| 語法直觀,設計師友善 | 業務邏輯滲入視圖層,違反 MVC 分層 |
| 可集中在插件處理權限、快取、過濾 | 編譯錯誤難以除錯(發生在模板編譯階段) |
{fetch} 思路){load cache=300 ...}