freeMaker使用方式總結
- 地址。。。。http://liudaoru.iteye.com/blog/315224
- l FreeMarker是一個模板引擎,一個基於模板生成文本輸出的通用工具,使用純Java編寫
- l FreeMarker被設計用來生成HTML Web頁面,特別是基於MVC模式的應用程序
- l 雖然FreeMarker具備一些編程的能力,但一般由Java程序準備要顯示的數據,由FreeMarker生成頁面,經過模板顯示準備的數據(以下圖)
- l FreeMarker不是一個Web應用框架,而適合做爲Web應用框架一個組件
- l FreeMarker與容器無關,由於它並不知道HTTP或Servlet;FreeMarker一樣能夠應用於非Web應用程序環境
- l FreeMarker更適合做爲Model2框架(如Struts)的視圖組件,你也能夠在模板中使用JSP標記庫
- l FreeMarker是免費的
- 1、通用目標
- l 可以生成各類文本:HTML、XML、RTF、Java源代碼等等
- l 易於嵌入到你的產品中:輕量級;不須要Servlet環境
- l 插件式模板載入器:能夠從任何源載入模板,如本地文件、數據庫等等
- l 你能夠按你所需生成文本:保存到本地文件;做爲Email發送;從Web應用程序發送它返回給Web瀏覽器
- 2、強大的模板語言
- l 全部經常使用的指令:include、if/elseif/else、循環結構
- l 在模板中建立和改變變量
- l 幾乎在任何地方均可以使用複雜表達式來指定值
- l 命名的宏,能夠具備位置參數和嵌套內容
- l 名字空間有助於創建和維護可重用的宏庫,或者將一個大工程分紅模塊,而沒必要擔憂名字衝突
- l 輸出轉換塊:在嵌套模板片斷生成輸出時,轉換HTML轉義、壓縮、語法高亮等等;你能夠定義本身的轉換
- 3、通用數據模型
- l FreeMarker不是直接反射到Java對象,Java對象經過插件式對象封裝,以變量方式在模板中顯示
- l 你可使用抽象(接口)方式表示對象(JavaBean、XML文檔、SQL查詢結果集等等),告訴模板開發者使用方法,使其不受技術細節的打擾
- 4、爲Web準備
- l 在模板語言中內建處理典型Web相關任務(如HTML轉義)的結構
- l 可以集成到Model2 Web應用框架中做爲JSP的替代
- l 支持JSP標記庫
- l 爲MVC模式設計:分離可視化設計和應用程序邏輯;分離頁面設計員和程序員
- 5、智能的國際化和本地化
- l 字符集智能化(內部使用UNICODE)
- l 數字格式本地化敏感
- l 日期和時間格式本地化敏感
- l 非US字符集能夠用做標識(如變量名)
- l 多種不一樣語言的相同模板
- 6、強大的XML處理能力
- l <#recurse> 和<#visit>指令(2.3版本)用於遞歸遍歷XML樹
- l 在模板中清楚和直覺的訪問XML對象模型
- FreeMarker設計指南(1)
- 1、快速入門
- (1)模板 + 數據模型 = 輸出
- l FreeMarker基於設計者和程序員是具備不一樣專業技能的不一樣個體的觀念
- l 他們是分工勞動的:設計者專一於表示——建立HTML文件、圖片、Web頁面的其它可視化方面;程序員建立系統,生成設計頁面要顯示的數據
- l 常常會遇到的問題是:在Web頁面(或其它類型的文檔)中顯示的信息在設計頁面時是無效的,是基於動態數據的
- l 在這裏,你能夠在HTML(或其它要輸出的文本)中加入一些特定指令,FreeMarker會在輸出頁面給最終用戶時,用適當的數據替代這些代碼
- l 下面是一個例子:
- <html>
- <head>
- <title>Welcome!</title>
- </head>
- <body>
- <h1>Welcome ${user}!</h1>
- <p>Our latest product:
- <a href="${latestProduct.url}">${latestProduct.name}</a>!
- </body>
- </html>
- l 這個例子是在簡單的HTML中加入了一些由${…}包圍的特定代碼,這些特定代碼是FreeMarker的指令,而包含FreeMarker的指令的文件就稱爲模板(Template)
- l 至於user、latestProduct.url和latestProduct.name來自於數據模型(data model)
- l 數據模型由程序員編程來建立,向模板提供變化的信息,這些信息來自於數據庫、文件,甚至於在程序中直接生成
- l 模板設計者不關心數據從那兒來,只知道使用已經創建的數據模型
- l 下面是一個可能的數據模型:
- (root)
- |
- +- user = "Big Joe"
- |
- +- latestProduct
- |
- +- url = "products/greenmouse.html"
- |
- +- name = "green mouse"
- l 數據模型相似於計算機的文件系統,latestProduct能夠看做是目錄,而user、url和name看做是文件,url和name文件位於latestProduct目錄中(這只是一個比喻,實際並不存在)
- l 當FreeMarker將上面的數據模型合併到模板中,就建立了下面的輸出:
- <html>
- <head>
- <title>Welcome!</title>
- </head>
- <body>
- <h1>Welcome Big Joe!</h1>
- <p>Our latest product:
- <a href="products/greenmouse.html">green mouse</a>!
- </body>
- </html>
- (2)數據模型
- l 典型的數據模型是樹型結構,能夠任意複雜和深層次,以下面的例子:
- (root)
- |
- +- animals
- | |
- | +- mouse
- | | |
- | | +- size = "small"
- | | |
- | | +- price = 50
- | |
- | +- elephant
- | | |
- | | +- size = "large"
- | | |
- | | +- price = 5000
- | |
- | +- python
- | |
- | +- size = "medium"
- | |
- | +- price = 4999
- |
- +- test = "It is a test"
- |
- +- whatnot
- |
- +- because = "don't know"
- l 相似於目錄的變量稱爲hashes,包含保存下級變量的惟一的查詢名字
- l 相似於文件的變量稱爲scalars,保存單值
- l scalars保存的值有兩種類型:字符串(用引號括起,能夠是單引號或雙引號)和數字(不要用引號將數字括起,這會做爲字符串處理)
- l 對scalars的訪問從root開始,各部分用「.」分隔,如animals.mouse.price
- l 另一種變量是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
- |
- +- whatnot
- |
- +- fruits
- |
- +- (1st) = "orange"
- |
- +- (2nd) = "banana"
- l 這種對scalars的訪問使用索引,如animals[0].name
- (3)模板
- l 在FreeMarker模板中能夠包括下面三種特定部分:
- Ø ${…}:稱爲interpolations,FreeMarker會在輸出時用實際值進行替代
- Ø FTL標記(FreeMarker模板語言標記):相似於HTML標記,爲了與HTML標記區分,用#開始(有些以@開始 ,在後面敘述)
- Ø 註釋:包含在<#--和-->(而不是<!--和-->)之間
- l 下面是一些使用指令的例子:
- Ø if指令
- <#if animals.python.price < animals.elephant.price>
- Pythons are cheaper than elephants today.
- <#else>
- Pythons are not cheaper than elephants today.
- </#if>
- Ø list指令
- <p>We have these animals:
- <table border=1>
- <tr><th>Name<th>Price
- <#list animals as being>
- <tr><td>${being.name}<td>${being.price} Euros
- </#list>
- </table>
- 輸出爲:
- <p>We have these animals:
- <table border=1>
- <tr><th>Name<th>Price
- <tr><td>mouse<td>50 Euros
- <tr><td>elephant<td>5000 Euros
- <tr><td>python<td>4999 Euros
- </table>
- Ø include指令
- <html>
- <head>
- <title>Test page</title>
- </head>
- <body>
- <h1>Test page</h1>
- <p>Blah blah...
- <#include "/copyright_footer.html">
- </body>
- </html>
- Ø 一塊兒使用指令
- <p>We have these animals:
- <table border=1>
- <tr><th>Name<th>Price
- <#list animals as being>
- <tr>
- <td>
- <#if being.size = "large"><b></#if>
- ${being.name}
- <#if being.size = "large"></b></#if>
- <td>${being.price} Euros
- </#list>
- </table>
- FreeMarker設計指南(3)
- 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 下面是支持的轉義序列:
- 轉義序列
- 含義
- \"
- 雙引號(u0022)
- \'
- 單引號(u0027)
- \\
- 反斜槓(u005C)
- \n
- 換行(u000A)
- \r
- Return (u000D)
- \t
- Tab (u0009)
- \b
- Backspace (u0008)
- \f
- Form feed (u000C)
- \l
- <
- \g
- >
- \a
- &
- \{
- {
- \xCode
- 4位16進制Unicode代碼
- n 有一類特殊的字符串稱爲raw字符串,被認爲是純文本,其中的\和{等不具備特殊含義,該類字符串在引號前面加r,下面是一個例子:
- ${r"${foo}"}
- ${r"C:\foo\bar"}
- 輸出的結果是:
- ${foo}
- C:\foo\bar
- Ø 數字
- n 直接輸入,不須要引號
- n 精度數字使用「.」分隔,不能使用分組符號
- n 目前版本不支持科學計數法,因此「1E3」是錯誤的
- n 不能省略小數點前面的0,因此「.5」是錯誤的
- n 數字8、+8、08和8.00都是相同的
- Ø 布爾值
- n true和false,不使用引號
- Ø 序列
- n 由逗號分隔的子變量列表,由方括號限定,下面是一個例子:
- <#list ["winter", "spring", "summer", "autumn"] as x>
- ${x}
- </#list>
- 輸出的結果是:
- winter
- spring
- summer
- autumn
- n 列表的項目是表達式,因此能夠有下面的例子:
- [2 + 2, [1, 2, 3, 4], "whatnot"]
- n 可使用數字範圍定義數字序列,例如2..5等同於[2, 3, 4, 5],可是更有效率,注意數字範圍沒有方括號
- n 能夠定義反遞增的數字範圍,如5..2
- Ø 散列(hash)
- n 由逗號分隔的鍵/值列表,由大括號限定,鍵和值之間用冒號分隔,下面是一個例子:
- {"name":"green mouse", "price":150}
- n 鍵和值都是表達式,可是鍵必須是字符串
- l 獲取變量
- Ø 頂層變量: ${variable},變量名只能是字母、數字、下劃線、$、@和#的組合,且不能以數字開頭
- Ø 從散列中獲取數據
- n 可使用點語法或方括號語法,假設有下面的數據模型:
- (root)
- |
- +- book
- | |
- | +- title = "Breeding green mouses"
- | |
- | +- author
- | |
- | +- name = "Julia Smith"
- | |
- | +- info = "Biologist, 1923-1985, Canada"
- |
- +- test = "title"
- 下面都是等價的:
- book.author.name
- book["author"].name
- book.author.["name"]
- book["author"]["name"]
- n 使用點語法,變量名字有頂層變量同樣的限制,但方括號語法沒有該限制,由於名字是任意表達式的結果
- Ø 從序列得到數據:和散列的方括號語法語法同樣,只是方括號中的表達式值必須是數字;注意:第一個項目的索引是0
- Ø 序列片段:使用[startIndex..endIndex]語法,從序列中得到序列片段(也是序列);startIndex和endIndex是結果爲數字的表達式
- Ø 特殊變量:FreeMarker內定義變量,使用.variablename語法訪問
- l 字符串操做
- Ø Interpolation(或鏈接操做)
- n 可使用${..}(或#{..})在文本部分插入表達式的值,例如:
- ${"Hello ${user}!"}
- ${"${user}${user}${user}${user}"}
- n 可使用+操做符得到一樣的結果
- ${"Hello " + user + "!"}
- ${user + user + user + user}
- n ${..}只能用於文本部分,下面的代碼是錯誤的:
- <#if ${isBig}>Wow!</#if>
- <#if "${isBig}">Wow!</#if>
- 應該寫成:
- <#if isBig>Wow!</#if>
- Ø 子串
- n 例子(假設user的值爲「Big Joe」):
- ${user[0]}${user[4]}
- ${user[1..4]}
- 結果是(注意第一個字符的索引是0):
- BJ
- ig J
- l 序列操做
- Ø 鏈接操做:和字符串同樣,使用+,下面是一個例子:
- <#list ["Joe", "Fred"] + ["Julia", "Kate"] as user>
- - ${user}
- </#list>
- 輸出結果是:
- - Joe
- - Fred
- - Julia
- - Kate
- l 散列操做
- Ø 鏈接操做:和字符串同樣,使用+,若是具備相同的key,右邊的值替代左邊的值,例如:
- <#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}>
- - Joe is ${ages.Joe}
- - Fred is ${ages.Fred}
- - Julia is ${ages.Julia}
- 輸出結果是:
- - Joe is 30
- - Fred is 25
- - Julia is 18
- l 算術運算
- Ø +、-、×、/、%,下面是一個例子:
- ${x * x - 100}
- ${x / 2}
- ${12 % 10}
- 輸出結果是(假設x爲5):
- -75
- 2.5
- 2
- Ø 操做符兩邊必須是數字,所以下面的代碼是錯誤的:
- ${3 * "5"} <#-- WRONG! -->
- Ø 使用+操做符時,若是一邊是數字,一邊是字符串,就會自動將數字轉換爲字符串,例如:
- ${3 + "5"}
- 輸出結果是:
- 35
- Ø 使用內建的int(後面講述)得到整數部分,例如:
- ${(x/2)?int}
- ${1.1?int}
- ${1.999?int}
- ${-1.1?int}
- ${-1.999?int}
- 輸出結果是(假設x爲5):
- 2
- 1
- 1
- -1
- -1
- l 比較操做符
- Ø 使用=(或==,徹底相等)測試兩個值是否相等,使用!= 測試兩個值是否不相等
- Ø =和!=兩邊必須是相同類型的值,不然會產生錯誤,例如<#if 1 = "1">會引發錯誤
- Ø Freemarker是精確比較,因此對"x"、"x "和"X"是不相等的
- Ø 對數字和日期可使用<、<=、>和>=,但不能用於字符串
- Ø 因爲Freemarker會將>解釋成FTL標記的結束字符,因此對於>和>=可使用括號來避免這種狀況,例如<#if (x > y)>
- Ø 另外一種替代的方法是,使用lt、lte、gt和gte來替代<、<=、>和>=
- l 邏輯操做符
- Ø &&(and)、||(or)、!(not),只能用於布爾值,不然會產生錯誤
- Ø 例子:
- <#if x < 12 && color = "green">
- We have less than 12 things, and they are green.
- </#if>
- <#if !hot> <#-- here hot must be a boolean -->
- It's not hot.
- </#if>
- l 內建函數
- Ø 內建函數的用法相似訪問散列的子變量,只是使用「?」替代「.」,下面列出經常使用的一些函數
- Ø 字符串使用的:
- n html:對字符串進行HTML編碼
- n cap_first:使字符串第一個字母大寫
- n lower_case:將字符串轉換成小寫
- n upper_case:將字符串轉換成大寫
- n trim:去掉字符串先後的空白字符
- Ø 序列使用的:
- n size:得到序列中元素的數目
- Ø 數字使用的:
- n int:取得數字的整數部分(如-1.9?int的結果是-1)
- Ø 例子(假設test保存字符串"Tom & Jerry"):
- ${test?html}
- ${test?upper_case?html}
- 輸出結果是:
- Tom & Jerry
- TOM & JERRY
- l 操做符優先順序
- 操做符組
- 操做符
- 後綴
- [subvarName] [subStringRange] . (methodParams)
- 一元
- +expr、-expr、!
- 內建
- ?
- 乘法
- *、 / 、%
- 加法
- +、-
- 關係
- <、>、<=、>=(lt、lte、gt、gte)
- 相等
- ==(=)、!=
- 邏輯and
- &&
- 邏輯or
- ||
- 數字範圍
- ..
- (4)Interpolation
- l Interpolation有兩種類型:
- Ø 通用Interpolation:${expr}
- Ø 數字Interpolation:#{expr}或#{expr; format}
- l 注意:Interpolation只能用於文本部分
- l 通用Interpolation
- Ø 插入字符串值:直接輸出表達式結果
- Ø 插入數字值:根據缺省格式(由#setting指令設置)將表達式結果轉換成文本輸出;可使用內建函數string格式化單個Interpolation,下面是一個例子:
- <#setting number_format="currency"/>
- <#assign answer=42/>
- ${answer}
- ${answer?string} <#-- the same as ${answer} -->
- ${answer?string.number}
- ${answer?string.currency}
- ${answer?string.percent}
- 輸出結果是:
- $42.00
- $42.00
- 42
- $42.00
- 4,200%
- Ø 插入日期值:根據缺省格式(由#setting指令設置)將表達式結果轉換成文本輸出;可使用內建函數string格式化單個Interpolation,下面是一個使用格式模式的例子:
- ${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")}
- ${lastUpdated?string("EEE, MMM d, ''yy")}
- ${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")}
- 輸出的結果相似下面的格式:
- 2003-04-08 21:24:44 Pacific Daylight Time
- Tue, Apr 8, '03
- Tuesday, April 08, 2003, 09:24:44 PM (PDT)
- Ø 插入布爾值:根據缺省格式(由#setting指令設置)將表達式結果轉換成文本輸出;可使用內建函數string格式化單個Interpolation,下面是一個例子:
- <#assign foo=true/>
- ${foo?string("yes", "no")}
- 輸出結果是:
- yes
- l 數字Interpolation的#{expr; format}形式能夠用來格式化數字,format能夠是:
- Ø mX:小數部分最小X位
- Ø MX:小數部分最大X位
- Ø 例子:
- <#-- If the language is US English the output is: -->
- <#assign x=2.582/>
- <#assign y=4/>
- #{x; M2} <#-- 2.58 -->
- #{y; M2} <#-- 4 -->
- #{x; m1} <#-- 2.6 -->
- #{y; m1} <#-- 4.0 -->
- #{x; m1M2} <#-- 2.58 -->
- #{y; m1M2} <#-- 4.0 -->
- FreeMarker設計指南(4)
- 4、雜項
- (1)用戶定義指令
- l 宏和變換器變量是兩種不一樣類型的用戶定義指令,它們之間的區別是宏是在模板中使用macro指令定義,而變換器是在模板外由程序定義,這裏只介紹宏
- l 基本用法
- Ø 宏是和某個變量關聯的模板片段,以便在模板中經過用戶定義指令使用該變量,下面是一個例子:
- <#macro greet>
- <font size="+2">Hello Joe!</font>
- </#macro>
- Ø 做爲用戶定義指令使用宏變量時,使用@替代FTL標記中的#
- <@greet></@greet>
- Ø 若是沒有體內容,也可使用:
- <@greet/>
- l 參數
- Ø 在macro指令中能夠在宏變量以後定義參數,如:
- <#macro greet person>
- <font size="+2">Hello ${person}!</font>
- </#macro>
- Ø 能夠這樣使用這個宏變量:
- <@greet person="Fred"/> and <@greet person="Batman"/>
- 輸出結果是:
- <font size="+2">Hello Fred!</font>
- and <font size="+2">Hello Batman!</font>
- Ø 宏的參數是FTL表達式,因此下面的代碼具備不一樣的意思:
- <@greet person=Fred/>
- Ø 這意味着將Fred變量的值傳給person參數,該值不只是字符串,還能夠是其它類型,甚至是複雜的表達式
- Ø 宏能夠有多參數,下面是一個例子:
- <#macro greet person color>
- <font size="+2" color="${color}">Hello ${person}!</font>
- </#macro>
- Ø 能夠這樣使用該宏變量:
- <@greet person="Fred" color="black"/>
- Ø 其中參數的次序是無關的,所以下面是等價的:
- <@greet color="black" person="Fred"/>
- Ø 只能使用在macro指令中定義的參數,而且對全部參數賦值,因此下面的代碼是錯誤的:
- <@greet person="Fred" color="black" background="green"/>
- <@greet person="Fred"/>
- Ø 能夠在定義參數時指定缺省值,如:
- <#macro greet person color="black">
- <font size="+2" color="${color}">Hello ${person}!</font>
- </#macro>
- Ø 這樣<@greet person="Fred"/>就正確了
- Ø 宏的參數是局部變量,只能在宏定義中有效
- l 嵌套內容
- Ø 用戶定義指令能夠有嵌套內容,使用<#nested>指令執行指令開始和結束標記之間的模板片段
- Ø 例子:
- <#macro border>
- <table border=4 cellspacing=0 cellpadding=4><tr><td>
- <#nested>
- </tr></td></table>
- </#macro>
- 這樣使用該宏變量:
- <@border>The bordered text</@border>
- 輸出結果:
- <table border=4 cellspacing=0 cellpadding=4><tr><td>
- The bordered text
- </tr></td></table>
- Ø <#nested>指令能夠被屢次調用,例如:
- <#macro do_thrice>
- <#nested>
- <#nested>
- <#nested>
- </#macro>
- <@do_thrice>
- Anything.
- </@do_thrice>
- 輸出結果:
- Anything.
- Anything.
- Anything.
- Ø 嵌套內容能夠是有效的FTL,下面是一個有些複雜的例子:
- <@border>
- <ul>
- <@do_thrice>
- <li><@greet person="Joe"/>
- </@do_thrice>
- </ul>
- </@border>
- 輸出結果:
- <table border=4 cellspacing=0 cellpadding=4><tr><td>
- <ul>
- <li><font size="+2">Hello Joe!</font>
- <li><font size="+2">Hello Joe!</font>
- <li><font size="+2">Hello Joe!</font>
- </ul>
- </tr></td></table>
- Ø 宏定義中的局部變量對嵌套內容是不可見的,例如:
- <#macro repeat count>
- <#local y = "test">
- <#list 1..count as x>
- ${y} ${count}/${x}: <#nested>
- </#list>
- </#macro>
- <@repeat count=3>${y?default("?")} ${x?default("?")} ${count?default("?")}</@repeat>
- 輸出結果:
- test 3/1: ? ? ?
- test 3/2: ? ? ?
- test 3/3: ? ? ?
- Ø
- l 在宏定義中使用循環變量
- Ø 用戶定義指令能夠有循環變量,一般用於重複嵌套內容,基本用法是:做爲nested指令的參數傳遞循環變量的實際值,而在調用用戶定義指令時,在<@…>開始標記的參數後面指定循環變量的名字
- Ø 例子:
- <#macro repeat count>
- <#list 1..count as x>
- <#nested x, x/2, x==count>
- </#list>
- </#macro>
- <@repeat count=4 ; c, halfc, last>
- ${c}. ${halfc}<#if last> Last!</#if>
- </@repeat>
- 輸出結果:
- 1. 0.5
- 2. 1
- 3. 1.5
- 4. 2 Last!
- Ø 指定的循環變量的數目和用戶定義指令開始標記指定的不一樣不會有問題
- n 調用時少指定循環變量,則多指定的值不可見
- n 調用時多指定循環變量,多餘的循環變量不會被建立
- (2)在模板中定義變量
- l 在模板中定義的變量有三種類型:
- Ø plain變量:能夠在模板的任何地方訪問,包括使用include指令插入的模板,使用assign指令建立和替換
- Ø 局部變量:在宏定義體中有效,使用local指令建立和替換
- Ø 循環變量:只能存在於指令的嵌套內容,由指令(如list)自動建立;宏的參數是局部變量,而不是循環變量
- l 局部變量隱藏(而不是覆蓋)同名的plain變量;循環變量隱藏同名的局部變量和plain變量,下面是一個例子:
- <#assign x = "plain">
- 1. ${x} <#-- we see the plain var. here -->
- <@test />
- 6. ${x} <#-- the value of plain var. was not changed -->
- <#list ["loop"] as x>
- 7. ${x} <#-- now the loop var. hides the plain var. -->
- <#assign x = "plain2"> <#-- replace the plain var, hiding does not mater here -->
- 8. ${x} <#-- it still hides the plain var. -->
- </#list>
- 9. ${x} <#-- the new value of plain var. -->
- <#macro test>
- 2. ${x} <#-- we still see the plain var. here -->
- <#local x = "local">
- 3. ${x} <#-- now the local var. hides it -->
- <#list ["loop"] as x>
- 4. ${x} <#-- now the loop var. hides the local var. -->
- </#list>
- 5. ${x} <#-- now we see the local var. again -->
- </#macro>
- 輸出結果:
- 1. plain
- 2. plain
- 3. local
- 4. loop
- 5. local
- 6. plain
- 7. loop
- 8. loop
- 9. plain2
- l 內部循環變量隱藏同名的外部循環變量,如:
- <#list ["loop 1"] as x>
- ${x}
- <#list ["loop 2"] as x>
- ${x}
- <#list ["loop 3"] as x>
- ${x}
- </#list>
- ${x}
- </#list>
- ${x}
- </#list>
- 輸出結果:
- loop 1
- loop 2
- loop 3
- loop 2
- loop 1
- l 模板中的變量會隱藏(而不是覆蓋)數據模型中同名變量,若是須要訪問數據模型中的同名變量,使用特殊變量global,下面的例子假設數據模型中的user的值是Big Joe:
- <#assign user = "Joe Hider">
- ${user} <#-- prints: Joe Hider -->
- ${.globals.user} <#-- prints: Big Joe -->
- (3)名字空間
- l 一般狀況,只使用一個名字空間,稱爲主名字空間
- l 爲了建立可重用的宏、變換器或其它變量的集合(一般稱庫),必須使用多名字空間,其目的是防止同名衝突
- l 建立庫
- Ø 下面是一個建立庫的例子(假設保存在lib/my_test.ftl中):
- <#macro copyright date>
- <p>Copyright (C) ${date} Julia Smith. All rights reserved.
- <br>Email: ${mail}</p>
- </#macro>
- <#assign mail = "jsmith@acme.com">
- Ø 使用import指令導入庫到模板中,Freemarker會爲導入的庫建立新的名字空間,並能夠經過import指令中指定的散列變量訪問庫中的變量:
- <#import "/lib/my_test.ftl" as my>
- <#assign mail="fred@acme.com">
- <@my .copyright date="1999-2002"/>
- ${my.mail}
- ${mail}
- 輸出結果:
- <p>Copyright (C) 1999-2002 Julia Smith. All rights reserved.
- <br>Email: jsmith@acme .com</p>
- jsmith@acme .com
- fred@acme .com
- 能夠看到例子中使用的兩個同名變量並無衝突,由於它們位於不一樣的名字空間
- l 可使用assign指令在導入的名字空間中建立或替代變量,下面是一個例子:
- <#import "/lib/my_test.ftl" as my>
- ${my.mail}
- <#assign mail="jsmith@other.com" in my>
- ${my.mail}
- l 輸出結果:
- jsmith@acme .com
- jsmith@other .com
- l 數據模型中的變量任何地方均可見,也包括不一樣的名字空間,下面是修改的庫:
- <#macro copyright date>
- <p>Copyright (C) ${date} ${user}. All rights reserved.</p>
- </#macro>
- <#assign mail = "${user}@acme.com">
- l 假設數據模型中的user變量的值是Fred,則下面的代碼:
- <#import "/lib/my_test.ftl" as my>
- <@my .copyright date="1999-2002"/>
- ${my.mail}
- l 輸出結果:
- <p>Copyright (C) 1999-2002 Fred. All rights reserved.</p>
- Fred@acme .com
- Freemarker - 幾個比較實用的例子 - -
- 用Freemarker作模本語言有一段時間了,列出幾個和JSP或者Velocity相比起來比較方便的用途,目的是引誘更多的人跳上Freemarker這個賊船,
- 1. String內置的JavaScript轉換: js_string
- 用途:用於JavaScript轉義,轉換',",換行等特殊字符
- 模板:
- <script>
- alert("${errorMessage?js_string}");
- </script>
- 輸出:
- <script>
- alert("Readonly\'s pet name is \"Cross Bone\"");
- </script>
- 2.內置的默認值處理:default
- 用途: 用於處理默認值
- 模本:
- User: ${userLogin.name?default("Anonymous")}
- <td>${(employee.department.manager.name)?default(" ")}</td>
- 輸出:
- User: Anonymous
- <td> </td>
- 注,能夠對整個對象樹加上(),再用內置處理器這種方便的作法,偶也是最近剛學會的,之前一直用很傻的方法作.....
- 3. Sequence內置的計數器: xxx_index
- 用途:顯示序號
- 模板:
- <#list employees as e>
- ${e_index}. ${e.name}
- </#list>
- 輸出:
- 1. Readonly
- 2. Robbin
- 4. Sequence內置的分段器: chunk
- 用途:某些比較BT的排版需求
- 模板:
- <#assign seq = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']>
- <#list seq?chunk(4) as row>
- <ul>
- <li><#list row as cell>${cell} </#list></li>
- </ul>
- </#list>
- <#list seq?chunk(4, '-') as row>
- <tr>
- <td><#list row as cell>${cell} </#list></td>
- </tr>
- </#list>
- 輸出:
- <ul>
- <li>a</li>
- <li>b</li>
- <li>c</li>
- <li>d</li>
- </ul>
- <ul>
- <li>e</li>
- <li>f</li>
- <li>g</li>
- <li>h</li>
- </ul>
- <ul>
- <li>i</li>
- <li>j</li>
- </ul>
- <tr>
- <td>a</td>
- <td>b</td>
- <td>c</td>
- <td>d</td>
- </tr>
- <tr>
- <td>e</td>
- <td>f</td>
- <td>g</td>
- <td>h</td>
- </tr>
- <tr>
- <td>i</td>
- <td>j</td>
- <td>-</td>
- <td>-</td>
- </tr>
歡迎關注本站公眾號,獲取更多信息