Blog信息 |
blog名称: 日志总数:1304 评论数量:2242 留言数量:5 访问次数:7591310 建立时间:2006年5月29日 |

| |
[FreeMarker]FreeMarker 2 指令说明 软件技术
lhwork 发表于 2006/12/15 9:46:01 |
FreeMarker 数据模型
在FreeMarker模板中使用的三种基本对象类型:Scalars、Hashes 和Sequences。在解释这些对象类型之前,我们先来看看数据模型。典型的数据模型是树型结构,可以有任意深的层次,比如说:
(root) | +- animals | | | +- mouse | | | | | +- size = "small" | | | | | +- price = 50 | | | +- elephant | | | | | +- size = "large" | | | | | +- price = 5000 | | | +- python | | | +- size = "medium" | | | +- price = 4999
这棵树上的每一片叶子在FreeMarker中就称为Scalars,用来存储单值。Scalars保存的值有两种类型:字符串(用引号括起,可以是单引
号或双引号)、数字(不要用引号将数字括起,这会作为字符串处理)、日期和boolean值。对scalars的访问要从root开始,各部分用“.”分
隔,如animals.mouse.price。树的每一个分支关联一个唯一的查询名字,例如“mouse”,“elephant”,这些分支充当了其他对象(size,price)的容器,这种结构则称为Hashes,参考Hashes的TDD定义。Sequences的作用与Hashes类似,也可以充当其它对象的容器,只是不使用变量名字,而使用数字索引:(root) | +- animals | | | +- (1st) | | | | | +- name = "mouse" | | | | | +- size = "small" | | | | | +- price = 50 | | | +- (2nd) | | | | | +- name = "elephant" | | | | | +- size = "large" | | | | | +- price = 5000 | | | +- (3rd) | | | +- name = "python" | | | +- size = "medium" | | | +- price = 4999可以通过animals[0].name来访问相应的Scalars。参考Sequences的TDD定义针对上面三种对象类型的操作,可以参看对象类型的各种操作
模板与指令
除了相关的文本外,在FreeMarker模板中可以包括下面三种特定部分:
${…}:称为插补(interpolations),FreeMarker会在输出时用实际值进行替代。指令:也叫FreeMarker标记,与HTML标记类似,但用#开始(有些以@开始,在后面叙述)。注释:包含在<#-- 和 -->(而不是<!--和-->)之间文本。
控制指令
if指令
if指令与大部分程式语言一样,也支持<#else if..>,不再赘述。
<#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today.<#else> Pythons are not cheaper than elephants today.</#if>
list指令
list指令将遍历Sequences里的每一个元素。list指令有两个隐含的特殊变量:
item_index 该变量将返回元素在Sequences里的索引值。item_has_next 该变量是boolean型,false表明该元素是Sequences里的最后一个元素。<p>We have these animals:<table border=1> <tr><th>Id<th>Name<th>Price <#list animals as being> <tr><td>${being_index+1}<td>${being.name}<td>${being.price} Euros </#list></table>上面的模板可以依次列印出三种动物的名字和价格,being_index和being_has_next则是它的特殊变量。可以用<#break>指令提前结束list循环。
switch指令
与其他语言的switch语句类似。<#switch being.size> <#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>
注意事项
FTL区分大小写,所以list是正确的FTL指令,而List不是;${name}和${NAME}是不同的Interpolation只能在文本中使用FTL标记不能位于另一个FTL标记内部。注释可以位于FTL标记和Interpolation内部。多余的空白字符会在模板输出时移除可用[#if..]来替代<#if..>,避免于HTML标记混淆。 |
|
|