PHP 端 define('SITE_NAME', 'MyCMS');,模板中直接調用:
{$smarty.const.SITE_NAME}
適用於全局配置、狀態碼、路徑常量等。
{assign}{* 字符串 *}
{assign var="title" value="文章列表"}
{* 數字/布爾 *}
{assign var="page" value=1}
{assign var="showAds" value=true}
{* 陣列 *}
{assign var="tags" value=['php','smarty','template']}
{* 變量引用 *}
{assign var="url" value="/article/$id"}
<h1>{$title}</h1>
<!-- 輸出:文章列表
-->
Smarty **不支援** ++、+=、-= 等簡寫運算符,需用 {assign} 重新賦值或 {math} 函數。
{assign var="i" value=0}
{foreach $articles as $article}
{assign var="i" value=$i+1}
<div class="item-{$i}">{$article.title}</div>
{/foreach}
{* 標準 Smarty 不內建 math,需載入插件或自定義 *}
{* 假設已註冊 *}
{math equation="x+1" x=$i assign="i"}
{section name=loop loop=$articles}
{$smarty.section.loop.index} {* 從 0 開始 *}
{$smarty.section.loop.iteration} {* 從 1 開始 *}
{$smarty.section.loop.first} {* 是否首項 *}
{$smarty.section.loop.last} {* 是否尾項 *}
{/section}
{* layout.tpl *}
<html>
<head><title>{block name=title}默認標題{/block}</title></head>
<body>
{block name=content}默認內容{/block}
</body>
</html>
{* child.tpl *}
{extends file="layout.tpl"}
{block name=title}文章詳情 - {$article.title}{/block}
{block name=content}
<article>{$article.content}</article>
{/block}
$smarty->assign() 傳入。user_name,避免與保留字衝突。{$var} 已啟用 escape:'html',輸出原始 HTML 用 {$var nofilter}(極謹慎)。$smarty->caching = true,設定 cache_lifetime,動態內容用 {nocache}{/nocache} 包裹。{$var|@var_dump} 或 {debug} 顯示所有模板變量。