`

FreeMarker指令学习

阅读更多

自己翻译官方文档,有些不大理解的没翻译出来。。由于字数有限,,只能上传附件了。。

附件上还有:FreeMarker中文文档.pdf

FreeMarker_Programmer Guide.pdf  中文版

 

if, else, elseif
语法:
<#if condition>
  ...
<#elseif condition2>
  ...
<#elseif condition3>
  ...
...
<#else>
  ...
</#if>
备注:condition、condition2···必须为boolean 类型,<#elseif ··>、<#else>可有0或多个。
实例:
 <#if x == 1>
  x is 1
<#elseif x == 2>
  x is 2
<#elseif x == 3>
  x is 3
<#elseif x &gt 4>
  x is 4
<#else>
  x is not 1 nor 2 nor 3 nor 4
</#if>   
备注:< 或 > 号 必须转义,否则出错。。转义请参考其他文档。

switch, case, default, break
语法
<#switch value>
  <#case refValue1>
    ...
    <#break>
  <#case refValue2>
    ...
    <#break>
  ...
  <#case refValueN>
    ...
    <#break>
  <#default>
    ...
</#switch>
备注:该指令官方不推荐使用了,可以用if, else, elseif 指令代替。

list, break
语法
<#list sequence as item>
    ...
</#list>
备注: sequence 为一个sequence 或者 collection 类型。item 为 循环的变量。该指令中包含有两个特殊的循环变量,
item_index:该值为当前循环的值。 item_has_next:该值为一个boolean类型,表明该循环是否含有下一个(是否为循环到了最后一个)
实例:
<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
  ${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list> 
输出:
  1. winter,
  2. spring,
  3. summer,
  4. autumn   
 实例:
<#assign x=3>
<#list 1..x as i>
  ${i}
</#list>  
备注:当x 为一个数值序列时,可以使用该list 列出两个数值之间的值。(适合于表格的序号填写)
实例:
<#list seq as x>
  ${x}
  <#if x = "spring"><#break></#if>
</#list>
备注:可以用<#if···><#break> 来终止该循环。

include
语法
<#include path>
或者
<#include path options>
备注:
path: 为包含一个文件的路径或者是一个输出为String 类型的表达式。 
options: 一个或多个的参数: encoding=encoding, parse=parse 
encoding: 包含文件解析的编码,如GBK、utf-8等
parse: 为一个boolean 类型值,true为用ftl解析,false为当作text文件解析 (also accepts a few string values for backward compatibility)
实例:
/common/copyright.ftl内容:
Copyright 2001-2002 ${me}<br>
All rights reserved.   
主体内容: 
<#assign me = "Juila Smith">
<h1>Some test</h1>
<p>Yeah.
<hr>
<#include "/common/copyright.ftl">   
 输出   
<h1>Some test</h1>
<p>Yeah.
<hr>
Copyright 2001-2002 Juila Smith
All rights reserved.   
备注:path 可以包含*任意取值,例如:*/copyright.ftl、commons/*/copyright.ftl等,*表示任意路径下的。
该指令具有国际化,如<#include "footer.ftl">, 这个指令的搜索文件的顺序为footer_en_US.ftl,footer_en.ftl,footer.ftl (本地为英国)。

import
语法:
<#import path as hash>
备注:
path:模板的路径名. 
hash: 在该文件中使用该模板指令的名称。
实例:
<#import "/libs/mylib.ftl" as my>
文件中的使用:
<@my.copyright date="1999-2002"/> 

noparse
语法:
<#noparse>
  ...
</#noparse>
备注:该指令包含的文件将不被解析成ftl,而是直接输出。
实例:
Example:
--------
<#noparse>
  <#list animals as being>
  <tr><td>${being.name}<td>${being.price} Euros
  </#list>
</#noparse>   
输出: 
 Example:
--------
  <#list animals as being>
  <tr><td>${being.name}<td>${being.price} Euros
  </#list>

compress
语法:
<#compress>
  ...
</#compress>
备注:该指令将会把数据模型中的空格或者html格式去掉。
实例:
<#assign x = "    moo  \n\n   ">
(<#compress>
  1 2  3   4    5
  ${moo}
  test only

  I said, test only

</#compress>) 
输出:
(1 2 3 4 5
moo
test only
I said, test only)

escape, noescape
语法:
<#escape identifier as expression>
  ...
  <#noescape>...</#noescape>
  ...
</#escape> 
备注:该指令对${```}该指令进行了格式化的输出。
备注:
<#escape x as x?html>
  Customer Name: ${customerName}
  Items to ship:
  <#escape x as itemCodeToNameMap[x]>
    ${itemCode1}
    ${itemCode2}
    ${itemCode3}
    ${itemCode4}
  </#escape>
</#escape>  
相当于:
Customer Name: ${customerName?html}
  Items to ship:
    ${itemCodeToNameMap[itemCode1]?html}
    ${itemCodeToNameMap[itemCode2]?html}
    ${itemCodeToNameMap[itemCode3]?html}
    ${itemCodeToNameMap[itemCode4]?html}

assign
语法:
<#assign name=value>
or
<#assign name1=value1 name2=value2 ... nameN=valueN>
or
<#assign same as above... in namespacehash>
or
<#assign name>
  capture this
</#assign>
or
<#assign name in namespacehash>
  capture this
</#assign>
备注:该指令可以创建或者替换变量为页面使用,该变量为最高的层才能被创建或替换,如foo,当foo.bar时将不能被创建或者替换。
name:变量的名称。value:变量的值。namespacehash:import指令中的引用名。
实例:
<#assign seasons = ["winter", "spring", "summer", "autumn"]> 
<#assign
  seasons = ["winter", "spring", "summer", "autumn"]
  test = test + 1
>
实例:  
<#import "/mylib.ftl" as my>
<#assign bgColor="red" in my>
实例:
 <#macro myMacro>foo</#macro>
<#assign x>
  <#list 1..3 as n>
    ${n} <@myMacro />
  </#list>
</#assign>
Number of words: ${x?word_list?size}
${x} 
输出:
Number of words: 6
    1 foo
    2 foo
    3 foo

global
语法:
<#global name=value>
or
<#global name1=value1 name2=value2 ... nameN=valueN>
or
<#global name>
  capture this
</#global>
备注:该指令相似于assign 指令,只是该指令创建的变量可以被所有命名空间使用。
实例:
<#global x = 1> 
<#assign x = 2>
${x}
${.global.x}
</#assign>
输出:
2
1
备注:如果在当前命名空间中,有同名的变量存在,则global 变量将没隐藏,如需访问则:${.global.x} 

local
语法:
<#local name=value>
or
<#local name1=value1 name2=value2 ... nameN=valueN>
or
<#local name>
  capture this
</#local>
备注:该指令类似 assign 指令,但它创建或者替换了本例变量,它只能在macro定义或者function 定义中有效。

setting
语法:
<#setting name=value>
备注:该指令的设置将影响到该指令设置的地方以下的内容有效。
它提供的设值有:
local:该值为本地的语言,将影响数值、时间等的格式。取值例如:en, en_US, en_US_MAC
number_format:用于将数值转换成String,当没有明确的格式被指定时。
boolean_format:用于将boolean转换成String
date_format,time_format,datetime_format:用于将时间转换成String
time_zone:用于设置时区,如"GMT", "GMT+2", "GMT-1:30", "CET", "PST", "America/Los_Angeles"
url_escaping_charset:
classic_compatible:
实例:
${1.2}
<#setting locale="en_US">
${1.2}  
输出:
1,2
1.2 

User-defined directive (<@...>)
语法:
<@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN/>
(Note the XML-style / before the >)  
or if you need loop variables 
<@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN ; lv1, lv2, ..., lvN/>

Or the same as the above two but with end-tag

<@user_def_dir_exp ...>
  ...
</@user_def_dir_exp>
or
<@user_def_dir_exp ...>
  ...
</@>

Or all above but with positional parameter passing 

<@ val1, val2, ..., valN/>
...etc.
备注:该指令为调用用户自定义的指令,比如macro
实例:
<@list items=["mouse", "elephant", "python"] title="Animals"/>
...
<#macro list title items>
  <p>${title?cap_first}:
  <ul>
    <#list items as x>
      <li>${x?cap_first}
    </#list>
  </ul>
</#macro>  
输出:
  <p>Animals:
  <ul>
      <li>Mouse
      <li>Elephant
      <li>Python
  </ul>
  
...  
实例:
<@myRepeatMacro count=4 ; x, last>
  ${x}. Something... <#if last> This was the last!</#if>
</@myRepeatMacro>  

macro, nested, return
语法:
<#macro name param1 param2 ... paramN>
  ...
  <#nested loopvar1, loopvar2, ..., loopvarN>
  ...
  <#return>
  ...
</#macro>
备注:该指令保存着模板的部分定义,可以用用户指令来调用该指令使用。该指令可以定义在任何地方,不管设定的地方之前或者之后都能使用。也可以指定默认参数的默认值。
实例:
<#macro test foo bar="Bar" baaz=-1>
  Test text, and the params: ${foo}, ${bar}, ${baaz}
</#macro>
<@test foo="a" bar="b" baaz=5*5-2/>
<@test foo="a" bar="b"/>
<@test foo="a" baaz=5*5-2/>
<@test foo="a"/>  
输出:
  Test text, and the params: a, b, 23
  Test text, and the params: a, b, -1
  Test text, and the params: a, Bar, 23
  Test text, and the params: a, Bar, -1
实例:
<#macro img src extra...>
  <img src="/context${src?html}" 
  <#list extra?keys as attr>
    ${attr}="${extra[attr]?html}"
  </#list>
  >
</#macro>
<@img src="/images/test.png" width=100 height=50 alt="Test"/> 
输出:
  <img src="/context/images/test.png"
    alt="Test"
    height="50"
    width="100"
  >  
实例:
<#macro do_thrice>
  <#nested 1>
  <#nested 2>
  <#nested 3>
</#macro>
<@do_thrice ; x>
  ${x} Anything.
</@do_thrice>  
输出:
  1 Anything.
  2 Anything.
  3 Anything.
实例:
<#macro test>
  Test text
  <#return>
  Will not be printed.
</#macro>
<@test/>  
输出:
Test text

function, return
语法:
<#function name param1 param2 ... paramN>
  ...
  <#return returnValue>
  ...
</#function>
备注:该指令创建了一个方法变量,该指令和macro指令类似,只是return 中必须有返回值。
实例:
<#function avg x y>
  <#return (x + y) / 2>
</#function>
${avg(10, 20)}  
输出:
15
实例:
<#function avg nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum = sum + num>
  </#list>
  <#if nums?size != 0>
    <#return sum / nums?size>
  </#if>
</#function>
${avg(10, 20)}
${avg(10, 20, 30, 40)}
${avg()!"N/A"}  
输出:
15
25
N/A

flush
语法:
<#flush>
备注:强制输出。虽然FreeMarker会自动的flush 但有些时候要强制flash 的时候可以使用该指令。

stop
语法:
<#stop>
or
<#stop reason>
备注:当FreeMarker要强制终止的时候,可以使用该指令,reason 为自定义终止的原因。

ftl
语法:
<#ftl param1=value1 param2=value2 ... paramN=valueN>
备注:该指令是提供一些参数如果该文件是ftl文件,如果该文件存在则该设置在文件的最开始的地方。
设置的参数有:
encoding:模板的编码,取值为:utf-8、GBK等
strip_whitespace:是否去掉空格。取值为true、false
strip_text:是否去掉最高层的文本,取值为true、false
strict_syntax:是否为严格的语法,取值为true、false
ns_prefixes:
attributes:

t, lt, rt
语法
<#t>  -在该行中忽略所有的空格
<#lt> -在该行中忽略左边的所有空格
<#rt> -在该行中忽略右边的所有空格
<#nt> -不去掉该行的空格

实例:
--
  1 <#t>
  2<#t>
  3<#lt>
  4
  5<#rt>
  6
--  
输出:
--
1 23
  4
  5  6
--  

attempt, recover
语法:
<#attempt>
  attempt block
<#recover>
  recover block
</#attempt>
备注:该指令是一个错误的捕获,和java 中的 try{}catch 相似。<#recover>是修复指令,代替出错的输出文本。
实例:
Primary content
<#attempt>
  Optional content: ${thisMayFails}
<#recover>
  Ops! The optional content is not available.
</#attempt>
Primary content continued  
输出:
如果thisMayFails 变量不存在
Primary content
  Ops! The optional content is not available.
Primary content continued 
如果thisMayFails 变量存在
Primary content
  Optional content: 123
Primary content continued

visit, recurse, fallback
语法:
<#visit node using namespace>
or
<#visit node>
<#recurse node using namespace>
or
<#recurse node>
or
<#recurse using namespace>
or
<#recurse>
<#fallback>
备注:visit 和recurse 指令是用来递归处理树节点的。在实际中,很多情况下是用来处理xml。
实例:
<#-- Assume that nodeWithNameX?node_name is "x" -->
<#visit nodeWithNameX>
Done.
<#macro x>
   Now I'm handling a node that has the name "x".
   Just to show how to access this node: this node has ${.node?children?size} children.
</#macro>  
输出:
Now I'm handling a node that has the name "x".
   Just to show how to access this node: this node has 3 children.
Done.  
实例:
主体
<#import "n1.ftl" as n1>
<#import "n2.ftl" as n2>

<#-- This will call n2.x (because there is no n1.x): -->
<#visit nodeWithNameX using [n1, n2]>

<#-- This will call the x of the current namespace: -->
<#visit nodeWithNameX>

<#macro x>
  Simply x
</#macro>
  
n1.ftl
<#macro y>
  n1.y
</#macro>

 n2.ftl:  
 <#macro x>
  n2.x
  <#-- This will call n1.y, becuase it inherits the "using [n1, n2]" from the pending visit call: -->
  <#visit nodeWithNameY>
  <#-- This will call n2.y: -->
  <#visit nodeWithNameY using .namespace>
</#macro>

<#macro y>
  n2.y
</#macro>   
 输出:
 n2.x
  n1.y
  n2.y

  Simply x

 

分享到:
评论
3 楼 wq13480 2010-01-11  
加上目录就更好了.
2 楼 zdz8207 2009-11-06  
博主总结得非常好,虽然我用了很久freemarker了,但还有很多地方是没有用过的,非常感谢!
1 楼 javacto 2009-10-21  

相关推荐

    FreeMarker学习资料

    FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成: 1,文本:直接输出的部分 2,注释:;...4,FTL指令:FreeMarker指定,和HTML标记类似,名字前加#予以区分,不会输出

    freemarker语法完整版

    B 指令 if, else, elseif 语法 Java代码 &lt;#if condition&gt; ... &lt;#elseif condition2&gt; ... &lt;#elseif condition3&gt; ... ... &lt;#else&gt; ... &lt;/#if&gt; ... ... ... ... ... 用例 ...

    超完整FreeMarker中文教程,代码

    什么是FreeMarker? ................................................................................................. 7 我们应该阅读什么内容? .............................................................

    Java学习指南(11) FreeMarker与MVC框架

    〖主要内容〗包含以下内容,具体以课程目录为准:* 开发环境与API* 基本类型的插值* Hash 与 Sequece类型的插值* 常用的 built-in 用法* 等指令的用法* 自定义函数 Method Variables * 共享变量 Shared ...

    FreeMark学习笔记

    如果全用不存在的指令,FreeMarker不会使用模板输出,而是产生一个错误消息.FreeMarker会忽略FTL标签中的空白字符.值得注意的是, /&gt; 和指令之间不允许有空白字符. 2, 插值规则 FreeMarker的插值有如下两种类型:1,...

    FreeMarker 手册

    FreeMarker 手册 .......................................................................................................... 1 用于 FreeMarker 2.3.18 .......................................................

    FreeMarker中文指导手册

    FreeMarker 手册 .......................................................................................................... 1 用于 FreeMarker 2.3.18 .......................................................

    2小时快速上手Freemarker电商项目商品详情页静态化

    在职开发人员学完后会让你的薪资更高,让你更了解互联网是如何解决高并发 学完SSM框架的同学就可以学习,能让你切身感受到企业级开发环境目标1:掌握Freemarker常用的指令与内建函数目标2:完成商品详细页的数据显示...

    深入浅出Struts 2 .pdf(原书扫描版) part 1

    书中概念清晰、环环相扣,便于读者高效地学习。《深入浅出Struts2》适合Java Web 程序员阅读和参考,也可以作为计算机相关专业教材。 编辑推荐 《深入浅出Struts2》是广受赞誉的Struts2优秀教程.它全面而深入地...

Global site tag (gtag.js) - Google Analytics