ITeye博客

freemarker的用法

wolfcame · 2012-09-19 14:30 · freemarker · 编程语言 · Markdown

Tips:

 

  1. 以#开头的指令是freemarker的内置指令,用户自动的的指令以@开头
  2. Freemarker区分大小写
  3. 指令之间有包裹内容时需要结束标记,没有内容时不需要结束标记<#if condition> xxx </#if> <#include "/file"> ;与内置指令不同用户自定义指令以@开头,并且在没有包裹内容时,需要增加'/'标记,如<@myDirection condition />
  4. Freemarker指令列表大全 点我
  5. Freemarker内置变量大全 点我 ,访问内置变量使用'.' ,如 当前时间${.now}
  6. Freemarker内置引用大全 点我 ,使用内置引用很简单,如处理字符串的内置引用${name?low_case?trim}
  7. FreeMarker never converts a string to a number automatically, but it may convert a number to a string automatically.
  8. An attempt to print boolean values with interpolation causes an error and aborts template processing. For example this will cause an error: ${a == 2} and will not print ''true'' or something like that.

变量显示
${user.name}

${user.name!"Anonymous"}
当name为空时,设置默认值为Anonymous;此处有个问题是,如果user也为空,会抛出错误。

${(user.name)!"Anonymous"}
可避免上面的问题,无论user为空还是user.name为空都没关系。

 

${(user.name)!}
当没有指定默认值时,等同于${(user.name)!""},如,"Welcome_${(user.name)!}_" 将输出 Welcome__

控制结构指令
<#if user.name=="PC">welcome ${user.name}</#if>

<#if user.name==1>
price 1
<#else>
price bigger than 1
</#if>

<#if user.name??>user.name undefined</#if>
<#if (user.name)??>user or user.name undefined</#if>

列表循环指令
<#list users as user>
${user.name}  ${user.age}
</#list>

页面包含指令
<#include "/footer.jsp">

注解指令
<#-- 这里是Freemarker的注解 -->

 

自动转义html,防止iframe等攻击

 

<#escape x as x?html>
  ...
  <p>Title: ${book.title}</p>
  <p>Description: <#noescape>${book.description}</#noescape></p>
  <h2>Comments:</h2>
  <#list comments as comment>
    <div class="comment">
      ${comment}
    </div>
  </#list>
  ...
</#escape>  

 

 

========================================================

 

Freemarker的基本类型

 

基础类型

String

Number

Date

 

容器类型

Hash表,没有顺序,根据key来获取value

数组,按照编号获取value

容器,使用list指令来获取,可以是数组也可以是hash表

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。