Smarty 內建函數是範本語言核心組成部分,不可被自訂函數覆蓋或修改。本文整理 8 個常用內建函數並附完整範例。
<?php
// init.inc.php
define('ROOT_PATH', dirname(__FILE__));
require ROOT_PATH . '/libs/Smarty.class.php';
$_tpl = new Smarty();
$_tpl->template_dir = ROOT_PATH . '/tpl/';
$_tpl->compile_dir = ROOT_PATH . './com/';
$_tpl->left_delimiter = '<{';
$_tpl->right_delimiter = '}>';
?>
// index.php
<?php
require 'init.inc.php';
global $_tpl;
$_tpl->display('index.tpl');
?>
| 屬性 | 類型 | 必要 | 預設 | 說明 |
|---|---|---|---|---|
| name | string | 否 | default | 捕獲區域名稱 |
| assign | string | 否 | n/a | 指定變數名儲存捕獲內容 |
<{capture name="foo"}>
這裡的內容不會直接顯示,會存入 $foo
<{/capture}>
<{$smarty.capture.foo}> {* 輸出捕獲內容 *}
| 屬性 | 類型 | 必要 | 預設 | 說明 |
|---|---|---|---|---|
| file | string | 是 | n/a | 配置檔名稱 |
| section | string | 否 | n/a | 區段名稱 |
| scope | string | 否 | local | 作用域:local/parent/global |
| global | boolean | 否 | No | 等同 scope=parent |
詳細用法請參考《Smarty 實戰(二)》。
| 屬性 | 類型 | 必要 | 預設 | 說明 |
|---|---|---|---|---|
| file | string | 是 | n/a | 子範本路徑 |
| assign | string | 否 | n/a | 將輸出存入指定變數而非直接顯示 |
| [var ...] | mixed | 否 | n/a | 傳遞給子範本的區域變數 |
{include file="header.tpl"}
{* body *}
{include file="footer.tpl"}
支援豐富的條件修飾詞:
| 修飾詞 | 含義 |
|---|---|
| eq / == | 等於 |
| ne / neq / != | 不等於 |
| gt / > | 大於 |
| lt / < | 小於 |
| lte / le / <= | 小於等於 |
| gte / ge / >= | 大於等於 |
| is even / is odd | 偶數 / 奇數 |
| not | 邏輯非 |
| mod | 取模 |
| div by / even by / odd by | 可整除 / 商為偶數 / 商為奇數 |
| && / || / () | 邏輯與/或/分組 |
使用時需與许數或常數以空格分隔。
用於輸出 { 與 }:
<{ldelim}>funcname<{rdelim}> 是 Smarty 函數。
{* 輸出:{funcname} 是 Smarty 函數。 *}
區塊內容不解析,直接輸出,適合內嵌 JavaScript:
<{literal}>
<script>
window.alert(new Date());
</script>
<{/literal}>
<{php}>
echo date("Y-m-d H:i:s");
<{/php}>
{* 輸出:2011-10-24 04:35:03 *}
移除區塊內首尾空白與換行,保持 HTML 輸出整潔:
<{strip}>
<div>
<span>Hello</span>
</div>
<{/strip}>
{* 輸出:Hello *}
foreach、section 等迴圈函數將於後續文章詳細說明。