火星文 技术研习社

Noname Cat, Keep Thinking
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

FreeMarker 试验田

Posted on 2006-11-25 08:40  剑廿三  阅读(1411)  评论(0)    收藏  举报
FreeMarker

最新版本: 2.3.8,2006-7-10
主页:http://freemarker.sourceforge.net/
下载:http://freemarker.sourceforge.net/freemarkerdownload.html
手册:http://freemarker.sourceforge.net/docs/index.html


测试:

·对象属性/方法、HashMap、对象数组、List遍历、遍历时排序、
·运行时选择 include、
·日期指定格式显示、
·人类阅读习惯数值表示、计算机阅读习惯数值表示、
·新闻索引时截断显示过长标题
·利用 Hash 键值对应表获得和计算 document.links[i] 中的序号(含错误处理)
·更复杂的综合型函数(根据 iTV 平台获得网页超链接)

org.stephencat.test.FMTest 类

/**
 * 
 
*/
package org.stephencat.test;
import freemarker.template.*;
import java.util.*;
import java.io.*;


/**
 * 
@author stephen
 *
 
*/
public class FMTest {
    
    
private String username;
    
private String city;
    
private Date borndate;
    
    
public String getCity() {
        
return city;
    }

    
public void setCity(String city) {
        
this.city = city;
    }

    
public String getUsername() {
        
return username;
    }

    
public void setUsername(String username) {
        
this.username = username;
    }

    
public Date getBorndate() {
        
return borndate;
    }

    
public void setBorndate(Date borndate) {
        
this.borndate = borndate;
    }

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) throws Exception  {
        
// TODO Auto-generated method stub
        
        
// 建立一个用户对象
        FMTest user = new FMTest();
        user.setCity(
"Guangzhou, P.R.China");
        user.setUsername(
"Stephen Cat");
        user.setBorndate(Calendar.getInstance().getTime());
        
        
// 建立一组多个用户对象
        FMTest user1 = new FMTest();
        user1.setUsername(
"Tom");
        FMTest user2 
= new FMTest();
        user2.setUsername(
"Jack");
        FMTest user3 
= new FMTest();
        user3.setUsername(
"Jenny");
        FMTest user4 
= new FMTest();
        user4.setUsername(
"Christina");
        
        
// 组成 List<User>
        List users = new ArrayList();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        
        
// 初始化 FreeMaker 设置
        Configuration cfg = new Configuration();
        
// 模板目录
        cfg.setDirectoryForTemplateLoading(new File("templates"));
        
// 如果当前是 Servlet 应该这样设置模板目录:
        
// cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
        
// 设置模板字符集编码
        cfg.setDefaultEncoding("utf-8");
        
// 设置模板文件,应该用 UTF-8 格式书写
        
// 在 Eclipse 的 Window -> Preferences -> General -> Workspace -> Text file encoding 里设置
        Template temp = cfg.getTemplate("test.ftl");
        
        
/* Create a data model */
        Map root 
= new HashMap();
        
        
// test map 
        Map latest = new HashMap();
        root.put(
"latestProduct", latest);
        latest.put(
"url""products/greenmouse.html");
        latest.put(
"name""green mouse");
        
        
// test ifelse and switch  case
        root.put("area""usa");
        root.put(
"username""Stephen Wong");
        
        
// test object 
        root.put("user", user);
        
        root.put(
"users", users);

        root.put("bigNumber", 300000);


        // test hash ...

        int listSize = 8;
        
        root.put("listSize", String.valueOf(listSize));
       
        String currentFocus = "china";
       
        root.put("platform", "ut");  // or "zte"        
        root.put("currentFocus", currentFocus);


        /* Merge data model with template */
        
        
//Writer out = new OutputStreamWriter(System.out);
        
//temp.process(root, out);
        
//out.flush();
        
        StringWriter writer 
= new StringWriter();
        temp.process(root, writer);
        System.out.println(writer.toString());
    }
}

以下是模板文件,放在项目目录下的 templates 子目录中,与 src 同级

test.ftl


testing number ...
bigNumber?c   is ${bigNumber?c}
bigNumber   is ${bigNumber}

testing map 
url is ${latestProduct.url}
name is ${latestProduct.name}

testing object 
name: ${user.username}
city: ${user.city}
date: ${user.borndate?string("yyyy年MM月dd日 hh点mm分ss秒")}

testing if  else 
<#if area="asia">
    
<#include "asia.ftl">
<#elseif area="usa">
    
<#include "usa.ftl">
<#else>
    
<#include "africa.ftl">
</#if>

testing switch  (spaces will be remained.)
<#switch area>
    
<#case "asia">
        
<#include "asia.ftl">
        
<#break>
    
<#case "usa">
        
<#include "usa.ftl">
        
<#break>
    
<#case "africa">
        
<#include "africa.ftl">
        
<#break>
    
<#default>
        I'm from Mars. My name is ${username}.
</#switch>

testing list 
<#list users as u>
${u.username}
</#list>

testing list sorted by username
<#list users?sort_by("username") as u>
${u.username}
</#list>

testing foreach 
${users[1].username}
${users[3].username}

testing macro

<#function columnTitleLength columnName>
<#if columnName = "english">
<#return 23>
<#else>
<#return 15>
</#if>
</#function>

<#macro titleShorter originalTitle titleLength>
<#if (originalTitle?length gt titleLength) >
${originalTitle?substring(0, titleLength)}...
<#else>
${originalTitle}
</#if>
</#macro>

<@titleShorter originalTitle=title titleLength=columnTitleLength("english") />
<@titleShorter originalTitle=titleCN titleLength=columnTitleLength("china") />
-----------------------------------

testing hash ...

<#assign focusID =
{
"china":listSize+0,
"oversea":listSize+1,
"coffee":listSize+2,
"other":listSize+3,
"prev":listSize+4,
"next":listSize+5,
"back":listSize+6
}>

<#assign focusSet=focusID?keys>
<#function getLinkSequence id>
<#if focusSet?seq_contains(id)>
<#return focusID[id]>
<#else>
<#return id>
</#if>
</#function>

${getLinkSequence(currentFocus)}
---------------------------------------------------------------

testing complex integrated function ...

<#-- 自动脚本: 根据 iTV 平台获得超链接 -->
<#function getLink id>
 <#if platform = "ut">
  <#--
   需要手工修改: 定义各功能链接的序号
   listSize: 明细表当前页的条目数
  -->
  <#assign focusID =
  {
  "china":listSize?number+0,
  "oversea":listSize?number+1,
  "coffee":listSize?number+2,
  "other":listSize?number+3,
  "prev":listSize?number+4,
  "next":listSize?number+5,
  "back":listSize?number+6
  }>
  <#-- 自动脚本: 取所有栏目链接的 id 名称 -->
  <#assign focusSet=focusID?keys>
  
  <#-- 自动脚本: 获得并返回对应的链接序号 -->
  <#if focusSet?seq_contains(id)>
   <#return focusID[id]>
  <#else>
   <#return id>
  </#if>
 <#else>
  <#-- 自动脚本: 直接返回链接的 id 名称 -->
  <#return "\""+id+"\"">
 </#if>
</#function>

${getLink(currentFocus)}



运行时选择引用(include)的模板:

asia.ftl

I'm an Asian. My name is ${username}.

usa.ftl
I'm an American. My name is ${username}.

africa.ftl
I'm an african. My name is ${username}.

输出


testing number ...
bigNumber?c   is 300000
bigNumber   is 300,000

testing map 
url is products/greenmouse.html
name is green mouse

testing object 
name: Stephen Cat
city: Guangzhou, P.R.China
date: 2006年11月25日 08点27分47秒

testing if  else 
I'm an American. My name is Stephen Wong.

testing switch  (spaces will be remained.)
I'm an American. My name is Stephen Wong.

testing list 
Tom
Jack
Jenny
Christina

testing list sorted by username
Christina
Jack
Jenny
Tom

testing foreach 
Jack
Christina

testing macro
abcdefghijklmnopqrstuvw...
一二三四五六七八九十一二三四五...

testing hash ...


9


注意:空行会被原封不动地输出...