FreeMarker 一些常用方法或注意事项

FreeMarker 一些常用方法或注意事项

参考资料:http://jiangsha.iteye.com/blog/372307

表达式转换类

${expression} 计算expression 并输出
#{ expression } 数字计算#{ expression ;format} 按格式输出数字format 为M 和m
M 表示小数点后最多的位数,m 表示小数点后最少的位数如
#{121.2322;m2M2} 输出121.23

数字循环

1..5 表示从1 到5 ,原型number..number

对浮点取整数

${123.23?int} 

输出 123

给变量默认值

${var?default("hello world")?html} 

如果var is null 那么将会被hello world 替代

判断对象是不是null

    <#if mouse?exists>  
          Mouse found  
    <#else>  

也可以直接${mouse?if_exists})输出布尔形

解决输出中文乱码问题

freemarker乱码的原因:
没有使用正确的编码格式读取模版文件,表现为模版中的中文为乱码
解决方法:在classpath上放置一个文件freemarker.properties,在里面写上模版文件的编码方式,比如
default_encoding=UTF-8
locale=zh_CN
注意:eclipse中除了xml文件、java文件外,默认的文件格式iso8859-1

**数据插入模版时,没有使用正确的编码,表现出模版中的新插入数据为乱码**
解决方法:在result的配置中,指定charset,s2的FreemarkerResult.java会将charset传递freemarker
    <action name="ListPersons" class="ListPersons">
    <result type="freemarker">
        <param name="location">/pages/Person/view.ftl</param>
        <param name="contentType"> text/html;charset=UTF-8
    </param>
    </result>
    </action>

提高freemarker的性能

在freemarker.properties中设置:
template_update_delay=60000
避免每次请求都重新载入模版,即充分利用cached的模版

尽量使用freemarker本身的提供的tag

使用S2 tags 的标签会在性能上有所损失

freemarker的标签种类

  • ${..}:FreeMarker will replace it in the output with the actual value of the thing in the curly brackets. They are called interpolation s.
  • # ,代表是FTL tags(FreeMarker Template Language tags) ,hey are instructions to FreeMarker and will not be printed to the output
    • <#if ...></#if>
    • <#list totalList as elementObject>...</#list>
  • @ ,代表用户自定义的标签
  • <#-- --> 注释标签,注意不是<!-- -->

    一些特殊的指令

  • r代表原样输出:${r"C:\foo\bar"}
  • <#list ["winter", "spring", "summer", "autumn"] as x>${x}</#list>
  • ?引出内置指令
    • String处理指令
      • html:特殊的html字符将会被转义,比如”<”,处理后的结果是<
      • cap_first 、lower_case 、upper_case
      • trim :除去字符串前后的空格
    • sequences处理指令
      • size :返回sequences的大小
    • numbers处理指令
      • int:number的整数部分,(e.g. -1.9?int is -1)

对于null,或者miss value,freemarker会报错

  • ?exists:旧版本的用法
  • !:default value operator,语法结构为: unsafe_expr !default_expr,比如${mouse!"No mouse."} 当mouse不存在时,返回default value;
    • (product.color)!”red” 这种方式,能够处理product或者color为miss value的情况;
    • 而product.color!”red”将只处理color为miss value的情况
    • ??: Missing value test operator ,测试是否为missing value
    • unsafe_expr ?? :product.color??将只测试color是否为null
      • (unsafe_expr )??:(product.color)??将测试product和color是否存在null
    <#if mouse??>  
      Mouse found  
    <#else>  
      No mouse found  
    </#if>  
    Creating mouse...  
    <#assign mouse = "Jerry">  
    <#if mouse??>  
      Mouse found  
    <#else>  
      No mouse found  
    </#if>  

猜你喜欢

转载自blog.csdn.net/lgj123xj/article/details/78943883