ThinkPHP 內建模板引擎功能強大,但項目遷移或團隊習慣可能需要整合 Smarty。本文記錄整合關鍵配置、模板變量分配、以及 ThinkPHP 模型常用查詢方法(select、find、鏈式操作)速查表。
在 Conf/config.php 中設置:
<?php
return array(
'TMPL_ENGINE_TYPE' => 'Smarty', // 指定模板引擎
// 'TMPL_L_DELIM' => '<{', // 左分隔符(可選)
// 'TMPL_R_DELIM' => '}>', // 右分隔符(可選)
// 注:若分隔符與 JS 框架衝突,建議改用 {literal}{/literal} 包裹 JS 代碼
);
?>
確保 Vendor/Smarty/Smarty.class.php 可被自動載入,或在入口文件手動 require_once。
<?php
class IndexAction extends Action {
public function index() {
$this->assign('title', '首頁');
$this->assign('list', array(1,2,3));
$this->display('Index:index'); // 渲染 Tpl/Index/index.html
}
}
?>
| 方法/鏈式 | 用途 | 示例 |
|---|---|---|
select() | 查詢多條,返回二維陣列 | $User->select() |
field('name,email') | 指定查詢字段 | $User->field('name')->select() |
where($map) | 條件構建 | $User->where('status=1')->select() |
order('id DESC') | 排序 | $User->order('create_time DESC')->select() |
limit(10) / limit(5,10) | 分頁/限制條數 | $User->limit(10)->select() |
group('category') | 分組 | $User->field('category,count(*) as c')->group('category')->select() |
having('c>5') | 分組後過濾 | 需配合 group 使用 |
table('prefix_user') | 指定表(含前綴) | $User->table('__USER__')->select() |
find() | 查詢單條,返回一維陣列 | $User->find(1) 或 $User->where(...)->find() |
getField('name') | 獲取單字段值 | $User->where('id=1')->getField('name') |
<?php
$User = D('User');
$count = $User->count(); // COUNT(*)
$maxId = $User->max('id'); // MAX(id)
$minPrice = $User->min('price'); // MIN(price)
$avgScore = $User->avg('score'); // AVG(score)
$sum = $User->sum('amount'); // SUM(amount)
// 以上方法均可鏈式 where/order 等
?>
| PHP 模板 | Smarty 模板 |
|---|---|
<?php echo $title; ?> | {$title} |
<?php foreach($list as $v): ?> | {foreach $list as $v} |
<?php if($v['status']): ?> | {if $v.status} |
<?php echo date('Y-m-d',$v['time']); ?> | {$v.time|date_format:'%Y-%m-%d'} |
<?php echo htmlspecialchars($v['content']); ?> | {$v.content|escape} |
{ },JS 物件字面量需用 {literal}{/literal} 包裹。Runtime/Cache/ 需可寫。Runtime/Cache/ 下對應文件或後台清空緩存。