Smarty:if函数
{if},{elseif},{else}
Smarty的{if}
条件判断和PHP的if 非常相似,只是增加了一些特性。 每个{if}
必须有一个配对的{/if}
. 也可以使用{else}
和 {elseif}
. 全部的PHP条件表达式和函数都可以在if内使用,如||, or, &&, and, is_array(), 等等.
如果开启了安全机制,那么只有在$php_functions
设置允许的PHP函数才能使用。 参见安全机制。
下面是可用的运算符列表,使用中都会放到元素的中间并且用空格分隔。 注意列表中[方括号]的是可选的,而且还会列出对应PHP的表达式。
运算符 | 别名 | 语法示例 | 含义 | 对应PHP语法 |
---|---|---|---|---|
== | eq | $a eq $b | 等于 | == |
!= | ne, neq | $a neq $b | 不等于 | != |
> | gt | $a gt $b | 大于 | > |
< | lt | $a lt $b | 小于 | < |
>= | gte, ge | $a ge $b | 大于等于 | >= |
<= | lte, le | $a le $b | 小于等于 | <= |
=== | $a === 0 | 绝对等于 | === | |
! | not | not $a | 非 (一元运算) | ! |
% | mod | $a mod $b | 取模 | % |
is [not] div by | $a is not div by 4 | 取模为0 | $a % $b == 0 | |
is [not] even | $a is not even | [非] 取模为0 (一元运算) | $a % 2 == 0 | |
is [not] even by | $a is not even by $b | 水平分组 [非] 平均 | ($a / $b) % 2 == 0 | |
is [not] odd | $a is not odd | [非] 奇数 (一元运算) | $a % 2 != 0 | |
is [not] odd by | $a is not odd by $b | [非] 奇数分组 | ($a / $b) % 2 != 0 |
Example 7.44. {if} 表达式
{if $name eq 'Fred'} Welcome Sir. {elseif $name eq 'Wilma'} Welcome Ma'am. {else} Welcome, whatever you are. {/if} {* an example with "or" logic *} {if $name eq 'Fred' or $name eq 'Wilma'} ... {/if} {* same as above *} {if $name == 'Fred' || $name == 'Wilma'} ... {/if} {* parenthesis are allowed *} {if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#} ... {/if} {* you can also embed php function calls *} {if count($var) gt 0} ... {/if} {* check for array. *} {if is_array($foo) } ..... {/if} {* check for not null. *} {if isset($foo) } ..... {/if} {* test if values are even or odd *} {if $var is even} ... {/if} {if $var is odd} ... {/if} {if $var is not odd} ... {/if} {* test if var is divisible by 4 *} {if $var is div by 4} ... {/if} {* test if var is even, grouped by two. i.e., 0=even, 1=even, 2=odd, 3=odd, 4=even, 5=even, etc. *} {if $var is even by 2} ... {/if} {* 0=even, 1=even, 2=even, 3=odd, 4=odd, 5=odd, etc. *} {if $var is even by 3} ... {/if}
Example 7.45. {if} 的更多例子
{if isset($name) && $name == 'Blog'} {* do something *} {elseif $name == $foo} {* do something *} {/if} {if is_array($foo) && count($foo) > 0} {* do a foreach loop *} {/if}