學習整理,如有侵權,請Email 告之
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指令
Ø list指令
輸出爲:
Ø include指令
Ø 一起使用指令
|