---
title: "freemarker整理"
author: "leo1211"
date: "2010-05-18T14:16:07Z"
tags: ["C#", "C++", "Eclipse", "Spring", "freemarker"]
categories: ["编程语言"]
slug: "freemarker"
draft: false
lastmod: "2010-05-18T14:16:07Z"
id: 668953
url: "https://leo1211.iteye.com/blog/668953"
---

（1）解决输出中文乱码问题：

     freemarker乱码的原因：

- 没有使用正确的编码格式读取模版文件,表现为模版中的中文为乱码

> 解决方法：在classpath上放置一个文件freemarker.properties，在里面写上模版文件的编码方式，比如
> 
> default\_encoding=UTF-8  
> locale=zh\_CN
> 
> 注意：eclipse中除了xml文件、java文件外，默认的文件格式iso8859-1

- 数据插入模版时，没有使用正确的编码，表现出模版中的新插入数据为乱码

> 解决方法：在result的配置中，指定charset，s2的FreemarkerResult.java会将charset传递freemarker

> &lt;action name="ListPersons" class="ListPersons"&gt;

> &lt;result type="freemarker"&gt;
> 
>     &lt;param name="location"&gt;/pages/Person/view.ftl&lt;/param&gt;
> 
>     **&lt;param name="contentType"&gt; text/html;charset=UTF-8**
> 
> &lt;/param&gt;
> 
> &lt;/result&gt;
> 
> &lt;/action&gt;

（2）提高freemarker的性能

> 在freemarker.properties中设置：
> 
> template\_update\_delay=60000    （古刹飞鹰注：单位是秒）
> 
> 避免每次请求都重新载入模版，即充分利用cached的模版

（3）尽量使用freemarker本身的提供的tag，使用S2 tags 的标签会在性能上有所损失

> Freemarker has support for iterating lists, displaying properties, including other templates, macro's, and so on. There is a small performance cost when using the S2 tags instead of the Freemarker equivalent (eg. &lt;s:property value="foo"/&gt; should be replaced by ${foo}).

（4）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
    
    - &lt;#if ...&gt;&lt;/#if&gt;
    - &lt;#list totalList as elementObject&gt;...&lt;/#list&gt;
  - @ ,代表用户自定义的标签
  - &lt;#-- --&gt; 注释标签，注意不是&lt;!-- --&gt;

（5）一些特殊的指令：

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

（6）对于null，或者miss value，freemarker会报错

- - `!：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`
  - `?exists:旧版本的用法`

> ```
> 比如：
> ```
> 
> ```
> <#if mouse??>
  Mouse found
<#else>
  No mouse found
</#if>
Creating mouse...
<#assign mouse = "Jerry">
<#if mouse??>
  Mouse found
<#else>
  No mouse found
</#if> 
> ```

（7）**模版值插入方式**（interpolation）

- - **通用方式**（Universal interpolations）：`${expression}`
    
    - `对于字符串：只是简单输出`
    - `对于数值，会自动根据local确定格式，称为human audience，否则称为computer audience，可以"?c",比如，`&lt;a href="/shop/details?id=${product.id**?c**}"&gt;Details...&lt;/a&gt;,因此这里的id是给浏览器使用的，不需要进行格式化，注意?c只对数值有效
    - 对于日期，会使用默认的日期格式转换，因此需要事先设置好默认的转换格式，包括`date_format`, `time_format`，`atetime_format`
    - `对于布尔值，不能输出，会报错并停止模版的执行，比如${a = 2}会出错，但是可以string built-in来进行转换`

 

`  `**数值处理，具体参考：Built-ins for numbers**

> [http://freemarker.org/docs/ref\_builtins\_number.html#ref\_builtin\_string\_for\_number](http://freemarker.org/docs/ref_builtins_number.html#ref_builtin_string_for_number "http://freemarker.org/docs/ref_builtins_number.html#ref_builtin_string_for_number")
> 
> 数值处理的例子：
> 
> **&lt;#setting number\_format="currency"/&gt;**  
> &lt;#assign answer=42/&gt;  
> ${answer}  
> ${answer?string}  &lt;#-- the same as ${answer} --&gt;  
> ${answer?string.number}  
> ${answer?string.currency}  
> ${answer?string.percent} 
> 
> 除了使用内置的formate，可以使用任何用[Java decimal number](http://java.sun.com/j2se/1.4/docs/api/java/text/DecimalFormat.html) [format syntax](http://java.sun.com/j2se/1.4/docs/api/java/text/DecimalFormat.html)书写的formate，比如
> 
> ```
> <#setting number_format="0.###E0"/>
${1234}
${12345?string("0.####E0")}
> ```
> 
> ```
> 更加方便的格式：
> ```
> 
> ```
> <#setting locale="en_US">
US people writes:        ${12345678?string(",##0.00")}
<#setting locale="hu">
Hungarian people writes: ${12345678?string(",##0.00")}
> ```
> 
> ```
>  
> ```
> 
> ```
> 日期处理，参考Built-ins for dates
> ```

> [**http://freemarker.org/docs/ref\_builtins\_date.html#ref\_builtin\_string\_for\_date**](http://freemarker.org/docs/ref_builtins_date.html#ref_builtin_string_for_date "http://freemarker.org/docs/ref_builtins_date.html#ref_builtin_string_for_date")
> 
> **日期处理的例子：**
> 
> ${openingTime?string.short}  
> ${openingTime?string.medium}  
> ${openingTime?string.long}  
> ${openingTime?string.full}
> 
> ${nextDiscountDay?string.short}  
> ${nextDiscountDay?string.medium}  
> ${nextDiscountDay?string.long}  
> ${nextDiscountDay?string.full}
> 
> ${lastUpdated?string.short}  
> ${lastUpdated?string.medium}  
> ${lastUpdated?string.long}  
> ${lastUpdated?string.full}

> ```
> 注意：
> ```
> 
> ```
> 由于java语言中的Date类型的不足，freemarker不能根据Date变量判断出变量包含的部分（日期、时间还是全部），在这种情况下，freemarker
> ```
> 
> ```
> 不能正确显示出${lastUpdated?string.short} 或者 simply ${lastUpdated}，因此，可以通过?date, ?time and ?datetime built-ins
> ```
> 
> ```
> 来帮助freemarker来进行判断，比如${lastUpdated?datetime?string.short}
> ```
> 
> ```
>  
> ```

> ```
> 除了使用内置的日期转换格式外，可以自己指定日期的格式，使用的是Java date format syntax，比如：
> ```
> 
> ```
> ${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")}
${lastUpdated?string("EEE, MMM d, ''yy")}
${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")} 
> ```

- - **数值专用方式**（Numerical interpolations）：`#{expression}` or `#{expression; format}，这是数值专用的输出方式，但是``最好使用通用方式的string built-in或者number_format来完成转换，Numerical interpolations方式将会被停用`

（8）创建自定义模版

> ```
> 创建：
> ```
> 
> ```
> <#macro greet>
  <font size="+2">Hello Joe!</font>
</#macro>
> ```
> 
> 使用：&lt;@greet&gt;&lt;[/@greet]()&gt; 或者&lt;@greet/&gt;