{if $condition}
条件成立
{elseif $other_condition}
其它条件成立
{else}
都不成立
{/if}
| 类别 | 运算符 | 示例 |
|---|---|---|
| 比较 | ==, !=, >, <, >=, <=, eq, neq, gt, lt, gte, lte | {if $a eq $b} |
| 逻辑 | and, or, not, &&, ||, ! | {if $a and $b} |
| 包含 | in, not in | {if $x in $arr} |
| 整除 | is [not] div by | {if $i is div by 3} |
| 奇偶 | is [not] even/odd | {if $i is odd} |
| 类型 | is [not] int/float/string/array/object | {if $v is array} |
| 空值 | isset, empty | {if isset($var)} |
<?php
$cond = 1;
$smarty->assign('cond', $cond);
<table>
{if $cond == 1}
<tr><td>条件成立</td></tr>
{else}
<tr><td>条件不成立</td></tr>
{/if}
</table>
{if $user.logged and $user.role eq 'admin'}
<a href="/admin">后台管理</a>
{elseif $user.logged}
<a href="/profile">个人中心</a>
{else}
<a href="/login">登录</a>
{/if}
{$allowed = ['admin','editor','author']}
{if $user.role in $allowed}
显示编辑按钮
{/if}
{foreach $items as $item name=loop}
<div class="item {if $smarty.foreach.loop.iteration is odd}odd{else}even{/if}">
{$item.title}
</div>
{/foreach}
{if isset($title)}
<h1>{$title}</h1>
{/if}
{if $content != ''}
<div class="content">{$content}</div>
{/if}
{$status = $user.active ? '正常' : '禁用'}
// 或直接输出
{$user.active ? '正常' : '禁用'}
{capture name=msg}
{if $error}错误: {$error}{/if}
{/capture}
{if $smarty.capture.msg}
<div class="alert">{$smarty.capture.msg}</div>
{/if}
{* parent.tpl *}
<body>
{block name=content}{/block}
{if $show_footer}
{block name=footer}默认底部{/block}
{/if}
</body>
{if $show_xxx}if/elseif,改用策略模式或查找表{if $var|@count} 判断数组非空(见下文){if $arr|@count gt 0} 或 {if $arr|@count}(非空即真){if isset($var)} 语义更清晰。熟练运用 {if} 及其丰富运算符,让模板逻辑清晰可控。