環境設定 (config.inc.php)
<?php
require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('./templates');
$smarty->setCompileDir('./templates_c');
$smarty->setCacheDir('./cache');
$smarty->setConfigDir('./configs');
$smarty->caching = false; // 開發關閉快取
$smarty->left_delimiter = '<{';
$smarty->right_delimiter = '}>'; // 避免與前端框架衝突
?>
PHP 端指派變數 (index.php)
<?php
require 'config.inc.php';
$title = 'PHP 測試標題';
$content = 'Smarty 練習!';
$newsList = [
['name' => 'PHP 程式測試', 'date' => '2015-08-01'],
['name' => 'PHP 影音教學', 'date' => '2015-08-02'],
['name' => 'Smarty 學習', 'date' => '2015-08-03'],
];
$tableHeader = ['標題', '姓名', '年齡'];
$smarty->assign('title', $title);
$smarty->assign('content', $content);
$smarty->assign('newsList', $newsList); // 二維陣列
$smarty->assign('header', $tableHeader); // 一維陣列
$smarty->display('index.tpl');
?>
模板檔 (templates/index.tpl)
<h1><{$title}></h1>
<p>測試內容:<{$content}></p>
<h3>表格測試</h3>
<table border="1">
<tr><{foreach $header as $h}><th><{$h}></th><{/foreach}></tr>
<{foreach $newsList as $row}>
<tr>
<td><{$row.name}></td>
<td><{$row.date}></td>
</tr>
<{/foreach}>
</table>
常用修飾器 (Modifiers)
| 修飾器 | 說明 | 範例 |
escape | HTML 轉義 | <{$var|escape}> |
escape:"htmlall" | 全字元實體化 | <{$var|escape:'htmlall'}> |
truncate:30:"..." | 截斷字串 | <{$longText|truncate:30:'...'}> |
date_format:"%Y-%m-%d" | 日期格式化 (需 timestamp) | <{$timestamp|date_format:'%Y-%m-%d'}> |
upper/lower | 大小寫轉換 | <{$name|upper}> |
default:"預設值" | 變數為空時顯示預設 | <{$var|default:'無資料'}> |
進階技巧
- 區塊函數:
<{foreach}>, <{section}>, <{if}> 控制流程
- 模板繼承:
<{extends file='layout.tpl'}> + <{block name='content'}>
- 快取:
$smarty->caching = true; $smarty->cache_lifetime = 3600;
- 自訂函數/修飾器:
$smarty->registerPlugin('modifier', 'my_modifier', 'my_func');
輸出結果預覽
測試標題:PHP 測試標題
測試內容:Smarty 練習!
表格測試:
標題 | 姓名 | 年齡
PHP 程式測試 | 2015-08-01
PHP 影音教學 | 2015-08-02
Smarty 學習 | 2015-08-03
- 上一篇文章: PHP 簡易防盜鏈驗證實作教學
- 下一篇文章: PHP 使用 escapeshellarg 時中文被過濾的解決方案
Copyright ©
程式碼之家 All Rights Reserved