{if $condition}
條件成立時顯示
{elseif $other_condition}
其他條件成立
{else}
都不成立時顯示
{/if}
<html>
<head><title>Smarty Test</title></head>
<body>
<table width="200" border="0">
{if $cond == 1}
<tr><td>條件成立</td></tr>
{else}
<tr><td>條件不成立</td></tr>
{/if}
</table>
</body>
</html>
<?php
require 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->assign("cond", 1); // 或 0
$smarty->display('test6.htm');
?>
| 類別 | 運算子 | 範例 |
|---|---|---|
| 比較 | ==, !=, >, <, >=, <=, ===, !== | {if $age >= 18} |
| 邏輯 | and, or, not, &&, ||, ! | {if $a and $b} |
| 包含 | in, not in | {if $role in ['admin','editor']} |
| 存在 | isset, empty | {if isset($var)} |
| 正則 | matches, not matches | {if $email matches '/^.+@.+\..+$/'} |
| 奇偶 | is even, is odd | {if $i is even} |
| 可除 | is divisible by | {if $count is divisible by 3} |
{if $score >= 90}
<span class="excellent">優秀</span>
{elseif $score >= 80}
<span class="good">良好</span>
{elseif $score >= 60}
<span class="pass">及格</span>
{else}
<span class="fail">不及格</span>
{/if}
{if $user.roles in ['admin', 'superadmin']}
<a href="/admin">管理後台</a>
{/if}
{if $items|@count > 0}
{foreach $items as $item}
<li>{$item.name}</li>
{/foreach}
{else}
<p>暫無資料</p>
{/if}
{if $name|strlen > 20}
{$name|truncate:20:"..."}
{else}
{$name}
{/if}
// Smarty 內部編譯邏輯大致相當於:
if ($this->_tpl_vars['cond'] == 1) {
echo '條件成立';
} else {
echo '條件不成立';
}
{* ❌ 錯誤:少結束標籤 *}
{if $cond} 內容
{* ❌ 錯誤:else 位置錯誤 *}
{if $cond} 內容 {else} 內容 {/if} {else} 多餘
{* ✅ 正確:巢狀 if *}
{if $a}
{if $b} 內容 {/if}
{/if}
{* ✅ 正確:複雜邏輯用括號 *}
{if ($a > 10) and ($b < 5) or ($c == 'test')}
內容
{/if}
$showAdmin = $user->isAdmin(){capture} 暫存複雜判斷結果Smarty 條件判斷語法直觀強大,支援豐富運算子,善用可大幅簡化模板邏輯。