freemarker学习总结

来源:互联网 发布:赫子铭离婚 知乎 编辑:程序博客网 时间:2024/05/17 23:03

最近比较郁闷,sourceforge进不去,freemarker和hibernate等都托管于sourceforge,于是自己做一点学习记录,仅为了方便日后使用方便查阅
汇总freemarker标签
1.${...}插值
2.FTL Tags标签,FTL是区分大小写的,如<#break>标签等等,自定义标签用<@myTag>...</@myTag>
3. comments注释,<#-- 被注释的内容 -->
4.directives指令,跟html标签的使用方式一样,与FTL标签同义词

基本用法
1.if的使用
<#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> 
2.list的使用
<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
  ${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>  
output:
  1. winter,
  2. spring,
  3. summer,
  4. autumn 

item_index: This is a numerical value that contains the index of the current item being stepped over in the loop.
item_has_next: Boolean value that tells if the current item the last in the sequence or not.
<#assign x=3>
<#list 1..x as i>
  ${i}
</#list>  

output:
  1
  2
  3
<#list seq as x>
  ${x}
  <#if x = "spring"><#break></#if>
</#list>  

3.include
<#include "copyright_footer.html" >
4.处理不存在变量
${var!defaultvalue}  <#--设置默认值-->
<#if user??><h1>Welcome ${user}!</h1></#if>   <#--检查是否存在,如果user不存在if里面被忽略掉-->

5.用户自定义指令,跟函数/方法一样

<#macro name>:自定义标签<@name>:使用自定义标签<#inclode path>:引入子定义的模板<#improt path as mySpace>:创建一个空间,在引入的模板文件使用两个或两个以上的<#macro>时使用的

使用macro标签来定义<#macro greet person color="red"><font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
macro 指令自身不打印任何内容,它只是用来创建宏变量,所以就会有一个名为greet 的变量
宏的使用:
<@greet person="Fred" color="black"/>
output:
<font size="+2" color="black">Hello Fred!</font>

6.内建函数和方法调用
内建函数:如,name?upper_case,还有其他
 字符串使用的内建函数:
 html: 字符串中所有的特殊HTML 字符都需要用实体引用来代替(比如<代替<)。
 cap_first:字符串的第一个字母变为大写形式
 lower_case:字符串的小写形式
 upper_case:字符串的大写形式
 trim:去掉字符串首尾的空格
 序列使用的内建函数:
 size:序列中元素的个数
 数字使用的内建函数:
 int:数字的整数部分(比如-1.9?int 就是-1)
方法调用:${repeat("What", 3)}

附:注意事项
FTL 标签不可以在其他FTL 标签和插值中使用
如:<#if <#include 'foo'>='bar'>...</#if>是错的
但注释可以放在FTL 标签和插值中间,如${usre <#-- The name of user -->}
参考:http://freemarker.sourceforge.net/docs/ref.html

原创粉丝点击