3、模板
(1)整體結構
l 模板使用FTL(FreeMarker模板語言)編寫,是下面各部分的一個組合:
Ø 文本:直接輸出
Ø Interpolation:由${和},或#{和}來限定,計算值替代輸出
Ø FTL標記:FreeMarker指令,和Html標記類似,名字前加#予以區分,不會輸出
Ø 注釋:由<#--和-->限定,不會輸出
l 下面是以一個具體模板例子:
<html>[BR]
<head>[BR]
<title>Welcome!</title>[BR]
</head>[BR]
<body>[BR]
<#-- Greet the user with his/her name -->[BR]
<h1>Welcome ${user}!</h1>[BR]
<p>We have these animals:[BR]
<ul>[BR]
<#list animals as being>[BR]
<li>${being.name} for ${being.PRice} Euros[BR]
</#list>[BR]
</ul>[BR]
</body>[BR]
</html>
l [BR]是用于換行的非凡字符序列
l 注重事項:
Ø FTL區分大小寫,所以list是正確的FTL指令,而List不是;${name}和${NAME}是不同的
Ø Interpolation只能在文本中使用
Ø FTL標記不能位于另一個FTL標記內部,例如:
<#if <#include 'foo'>='bar'>...</if>
Ø 注釋可以位于FTL標記和Interpolation內部,如下面的例子:
<h1>Welcome ${user <#-- The name of user -->}!</h1>[BR]
<p>We have these animals:[BR]
<ul>[BR]
<#list <#-- some comment... --> animals as <#-- again... --> being>[BR]
...
Ø 多余的空白字符會在模板輸出時移除
(2)指令
l 在FreeMarker中,使用FTL標記引用指令
l 有三種FTL標記,這和HTML標記是類似的:
Ø 開始標記:<#directivename parameters>
Ø 結束標記:</#directivename>
Ø 空內容指令標記:<#directivename parameters/>
l 有兩種類型的指令:預定義指令和用戶定義指令
l 用戶定義指令要使用@替換#,如<@mydirective>...</@mydirective>(會在后面講述)
l FTL標記不能夠交叉,而應該正確的嵌套,如下面的代碼是錯誤的:
<ul>
<#list animals as being>
<li>${being.name} for ${being.price} Euros
<#if use = "Big Joe">
(except for you)
</#list>
</#if> <#-- WRONG! -->
</ul>
l 假如使用不存在的指令,FreeMarker不會使用模板輸出,而是產生一個錯誤消息
l FreeMarker會忽略FTL標記中的空白字符,如下面的例子:
<#list[BR]
animals as[BR]
being[BR]
>[BR]
${being.name} for ${being.price} Euros[BR]
</#list >
l 但是,<、</和指令之間不答應有空白字符
(3)表達式
l 直接指定值
Ø 字符串
n 使用單引號或雙引號限定
n 假如包含非凡字符需要轉義,如下面的例子:
${"It's /"quoted/" and
this is a backslash: //"}
${'It/'s "quoted" and
this is a backslash: //'}
輸出結果是:
It's "quoted" and
this is a backslash: /
It's "quoted" and
this is a backslash: /
n 下面是支持的轉義序列:
新聞熱點
疑難解答