如果,否则,否则

Page Contents

Synopsis

<#if condition>
  ...
<#elseif condition2>
  ...
<#elseif condition3>
  ...
...
<#else>
  ...
</#if>

Where:

  • conditioncondition2,...等:表达式的计算结果为布尔值。

elseif -s 和else是可选的。

骆驼的案例名称变体:elseIf

Description

您可以使用ifelseifelse指令有条件地跳过模板的一部分。 condition -s 必须计算为布尔值,否则错误将中止模板处理。 elseif -s 和else -s 必须出现在if内部(即,if起始标记和结束标记之间)。 if可以包含任意数量的elseif -s(包括 0),最后可以包含一个else。例子:

if与 0 elseif且没有else

<#if x == 1>
  x is 1
</#if>

if与 0 elseifelse

<#if x == 1>
  x is 1
<#else>
  x is not 1
</#if>

if与 2 elseif且没有else

<#if x == 1>
  x is 1
<#elseif x == 2>
  x is 2
<#elseif x == 3>
  x is 3
</#if>

if与 3 elseifelse

<#if x == 1>
  x is 1
<#elseif x == 2>
  x is 2
<#elseif x == 3>
  x is 3
<#elseif x == 4>
  x is 4
<#else>
  x is not 1 nor 2 nor 3 nor 4
</#if>

要了解有关布尔表达式的更多信息,请参见:模板作者指南/模板/表达式

您可以嵌套if指令(当然):

<#if x == 1>
  x is 1
  <#if y == 1>
    and y is 1 too
  <#else>
    but y is not
  </#if>
<#else>
  x is not 1
  <#if y < 0>
    and y is less than 0
  </#if>
</#if>

Note:

当您要测试x > 0x >= 0时,写<#if x > 0><#if x >= 0>是错误的,因为第一个>将关闭#if标记。要解决此问题,请写<#if x gt 0><#if gte 0>。还要注意,如果比较发生在括号内,则不会有此类问题,就像<#if foo.bar(x > 0)>可以正常工作一样。