首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

ThinkPHP 整合 Smarty 模板引擎配置與查詢方法匯總

     編輯:PHP 相關知識

ThinkPHP 整合 Smarty 模板引擎配置與查詢方法匯總

ThinkPHP 內建模板引擎功能強大,但項目遷移或團隊習慣可能需要整合 Smarty。本文記錄整合關鍵配置、模板變量分配、以及 ThinkPHP 模型常用查詢方法(select、find、鏈式操作)速查表。

Smarty 整合配置

在 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
    }
}
?>

ThinkPHP 模型查詢方法速查

方法/鏈式用途示例
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 等
?>

Smarty 模板中常用語法對照

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}

注意事項

  1. 分隔符衝突:若保留 Smarty 默認 { },JS 物件字面量需用 {literal}{/literal} 包裹。
  2. 緩存目錄權限:Runtime/Cache/ 需可寫。
  3. 編譯緩存清理:修改模板後需刪除 Runtime/Cache/ 下對應文件或後台清空緩存。
  4. ThinkPHP 3.2+ 內建引擎已支援佈局、區塊、輸出過濾等高級特性,非遷移項目建議優先使用內建引擎。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved