Freemarker 的常见控制结构写法(ZT)

来源:互联网 发布:电力监控软件布线 编辑:程序博客网 时间:2024/05/06 03:18
Freemarker是很好用的模板引擎。今天被一个小小的if...else...控制结构的写法困扰了很久,原来在freemaker里这个控制结构和JSTL还不一样,不了解的话还真是个问题。虽然freemarker的tag用的也是类似xml的尖括号,但是它并不遵守每个标签都要封口的规则。

选择结构
if...else...

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

只有一个if的情况:

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

包含elseif的情况:

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

包含else的用法:

<#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> 


switch...case...default...

<#switch value>
  <#case refValue1>
    ...
    <#break>
  <#case refValue2>
    ...
    <#break>
  <#case refValueN>
    ...
    <#break>
  <#default>
    ...
</#switch>

类似Java的普通用法:

<#switch being.size>
  <#case "small">
     This will be processed if it is small
     <#break>
  <#case "medium">
     This will be processed if it is medium
     <#break>
  <#case "large">
     This will be processed if it is large
     <#break>
  <#default>
     This will be processed if it is neither
</#switch>  

不使用break的方法,即在case中进行判断:

<#switch x>
  <#case x = 1>
    1
  <#case x = 2>
    2
  <#default>
    d
</#switch>  


循环迭代结构

<#list sequence as item>
    ...
</#list>

迭代的同时会生成两个变量:item_index,item_has_next,意如其名:

<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
  ${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>  

也可以用break跳出循环,用法和switch语句中的方法类似。
from http://classicning.javaeye.com/blog/99664
原创粉丝点击