Java模板引擎之FreeMarker超入门

字体大小: 中小 标准 ->行高大小: 标准
FreeMarker 是一个采用 Java 开发的模版引擎,是一个基于模版生成文本的通用工具。 它被设计用来生成 HTML Web 页面,特别是基于 MVC 模式的应用程序。虽然使用FreeMarker需要具有一些编程的能力,但通常由 Java 程序准备要显示的数据,由 FreeMarker 生成页面,并通过模板显示准备的数据。 

http://freemarker.org/ 

版本:2.3.19
 

Java代码  
  1. public void process(String template, Map<String, ?> data) throws Exception {  
  2.     Configuration cfg = new Configuration();  
  3.     cfg.setDirectoryForTemplateLoading(new File("ftl"));  
  4.     cfg.setObjectWrapper(new DefaultObjectWrapper());  
  5.       
  6.     //设置字符集  
  7.     cfg.setDefaultEncoding("UTF-8");  
  8.       
  9.     //设置尖括号语法和方括号语法,默认是自动检测语法  
  10.     //  自动 AUTO_DETECT_TAG_SYNTAX  
  11.     //  尖括号 ANGLE_BRACKET_TAG_SYNTAX  
  12.     //  方括号 SQUARE_BRACKET_TAG_SYNTAX  
  13.     cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);  
  14.   
  15.     Writer out = new OutputStreamWriter(new FileOutputStream(FILE_DIR + template + ".txt"),"UTF-8");  
  16.     Template temp = cfg.getTemplate(template);  
  17.     temp.process(data, out);  
  18.     out.flush();  
  19. }  


1、计算式 
引用

<#-- 1、算术运算 -->[BR] 
${3 + 4} 

<#-- 2、内建函数 -->[BR] 
${"rensanning"?upper_case} 


2、输出一个值 
Java代码  
  1. HashMap t2root = new HashMap<String, String>();  
  2. t2root.put("user""RenSanNing");  

引用
${user}, Welcome!


3、输出一个列表 
Java代码  
  1. Map<String, Object> t3root = new HashMap<String, Object>();  
  2. List<Food> menu = new ArrayList<Food>();  
  3. menu.add(new Food("iText in Action"98));  
  4. menu.add(new Food("iBATIS in Action"118));  
  5. menu.add(new Food("Lucene in Action"69));  
  6. t3root.put("menu", menu);  

引用

<#list menu as food> 
${food.name}  ${food.price?string.currency} 
</#list> 


4、逻辑判断(IF,SWITCH) 
Java代码  
  1. Map<String, Object> t4root = new HashMap<String, Object>();  
  2. t4root.put("x"2);  
  3. t4root.put("y""medium");  

引用

<1>if, else, elseif: 
<#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>switch, case, default, break: 
<#switch y> 
  <#case "small"> 
     This will be processed if it is small 
     <#break> 
  <#case "medium"> 
     This will be processed if it is medium 
     <#break> 
  <#case "large"> 
     This will be processed if it is large 
     <#break> 
  <#default> 
     This will be processed if it is neither 
</#switch> 

<3>list, break: 
<#assign seq = ["winter", "spring", "summer", "autumn"]> 
<#list seq as x> 
  ${x_index + 1}. ${x}<#if x_has_next>,</#if> 
</#list> 


5、自定义函数 
引用

<#function fact n> 
  <#if n == 0> 
    <#return 1 /> 
  <#else> 
    <#return fact(n - 1) * n /> 
  </#if> 
</#function> 

<#list 0..10 as i> 
  ${i}! => ${fact(i)} 
</#list> 


6、定义变量 
引用

<#-- 1、本地变量 -->[BR] 
<#function partg n lst> 
  <#local ans = []> 
  <#list lst as x> 
    <#if (x >= n)> 
      <#local ans = ans + [x]> 
    </#if> 
  </#list> 
  <#return ans> 
</#function> 

<#assign ls = [10, 2, 4, 5, 8, 1, 3]> 
<#list partg(4, ls) as x>${x} </#list> 

<#-- 2、变量域测试 -->[BR] 
<#macro test> 
    03. ${x} 
    <#global x = "global2"> 
    04. ${x} 
    <#assign x = "assign2"> 
    05. ${x} 
    <#local x = "local1"> 
    06. ${x} 
    <#list ["循环1"] as x> 
        07. ${x} 
        <#local x = "local2"> 
        08. ${x} 
        <#assign x = "assign3"> 
        09. ${x} 
    </#list> 
    10. ${x} 
</#macro> 

<#global x = "global1" /> 
01. ${x} 
<#assign x = "assign1" /> 
02. ${x} 
<@test /> 
11. ${x} 


7、定义宏macro 
引用

<#-- 1、无参数 -->[BR] 
<#macro greet> 
Welcome! 
</#macro> 

<@greet /> 

<#-- 2、有参数 -->[BR] 
<#macro greet user> 
${user}, Welcome! 
</#macro> 

<@greet user="RenSanNing"/> 

<#-- 3、有多个参数 -->[BR] 
<#macro table cols rows> 
  <table> 
    <#list 1..rows as row> 
      <tr> 
        <#list 1..cols as col> 
          <td>${row}, ${col}</td> 
        </#list> 
      </tr> 
    </#list> 
  </table> 
</#macro> 

<@table cols=3 rows=2 /> 

<#-- 4、中间跳出 -->[BR] 
<#macro out> 
  显示文字 
  <#return> 
  不显示文字 
</#macro> 

<@out /> 

<#-- 5、嵌套 -->[BR] 
<#macro lprint lst> 
  <#list lst as item> 
  ・${item}<#nested item /> 
  </#list> 
</#macro> 

<@lprint 1..3; x>^2 = ${x * x}</@lprint> 
<@lprint 1..3; x>^3 = ${x * x * x}</@lprint> 
<@lprint ["Let's go", "to the", "land of Medetai"] /> 


8、include 
引用

<#include "T108include.ftl"> 
${url} 
<@greet name="rensanning" /> 


T108include.ftl 
引用

<#macro greet name> 
${name}, Welcome! 
</#macro> 

<#assign url="http://www.baidu.com/"> 


9、名字空间 
引用

<#import "T109include.ftl" as my> 
<#assign url="http://www.google.com/"> 

${my.url} 
<@my.greet name="rensanning" /> 

${url} 


T109include.ftl 
引用

<#macro greet name> 
${name}, Welcome! 
</#macro> 

<#assign url="http://www.baidu.com/"> 


10、自定义指令Directive 

Java代码  
  1. public class SystemDateDirective implements TemplateDirectiveModel {  
  2.       
  3.     public void execute(Environment env, Map params, TemplateModel[] loopVars,  
  4.             TemplateDirectiveBody body) throws TemplateException, IOException {  
  5.         Calendar cal = Calendar.getInstance();  
  6.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
  7.         env.getOut().append(sdf.format(cal.getTime()));  
  8.     }  
  9.   
  10. }  


Java代码  
  1. public class TextCutDirective implements TemplateDirectiveModel {  
  2.     public static final String PARAM_S = "s";  
  3.     public static final String PARAM_LEN = "len";  
  4.     public static final String PARAM_APPEND = "append";  
  5.   
  6.     @SuppressWarnings("unchecked")  
  7.     public void execute(Environment env, Map params, TemplateModel[] loopVars,  
  8.             TemplateDirectiveBody body) throws TemplateException, IOException {  
  9.         String s = getString(PARAM_S, params);  
  10.         Integer len = getInt(PARAM_LEN, params);  
  11.         String append = getString(PARAM_APPEND, params);  
  12.         if (s != null) {  
  13.             Writer out = env.getOut();  
  14.             if (len != null) {  
  15.                 out.append(textCut(s, len, append));  
  16.             } else {  
  17.                 out.append(s);  
  18.             }  
  19.         }  
  20.     }  
  21.         
  22.         ....  


Java代码  
  1. Map<String, Object> t10root = new HashMap<String, Object>();  
  2. t10root.put("systemdate"new SystemDateDirective());  
  3. t10root.put("text_cut"new TextCutDirective());  


引用

<@systemdate/> 

<@text_cut s="汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字" len=10 append="..."/> 

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/68322.html