此片入門是對官網上的一個簡單的翻譯,想要快速了解freemaker並進行開發的,這一篇足已!
一、簡單介紹
在程序開發中,我們可能會頻繁使用到一些類似的片段,例如,展示文本的table,由於table的樣式基本一樣,只有數據是不一樣的,那我們可以考慮把這樣一個具有相同樣式的table做成一個模板。使用freemaker,可以簡單快捷的實現這一設計。下面來看一個簡單的freemaker的模板:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
這段模板和我們平時看到的靜態的html頁面一樣,是存儲在服務器上的,當用戶訪問的時候freemaker引擎能快速的把模板中的類似於${...}的內容替換成我們要展示的數據,最后展示給用戶的是一個html頁面,用戶並不會知道我們服務器端用的是freemaker(當然我們的模板在替換之后並不會改變任何的內容,因為這個替換只發生在服務器響應的過程中)。即將要替換到模板的數據我們統稱為data-model,這種數據是一個樹形結構,就像我們的電腦上的文件夾和文件一樣,可以被形象化這樣:
(root)
|
+- animals
| |
| +- mouse
| | |
| | +- size = "small"
| | |
| | +- price = 50
| |
| +- elephant
| | |
| | +- size = "large"
| | |
| | +- price = 5000
| |
| +- python
| |
| +- size = "medium"
| |
| +- price = 4999
|
+- message = "It is a test"
|
+- misc
|
+- foo = "Something"
這棵樹通常會相對的復雜和深,可以看到這些數據就像目錄一樣,我們稱為hashes,hashes 通常存儲着其他的一些變量(如上面看到的animals,message,misc,foo等)。
對於只存儲了單值的變量,如size,price等,我們稱之為scalars。另外一種特殊的變量是sequences,sequence存儲的子變量也像hashes一樣,但是這些變量沒有變量名,就像我們平時看到的數組一樣。scalars儲存的數據類型有:字符型、數組型、日期型、布爾型。
先來了解一點freemaker的基本語法
1、${...} 花括號內的內容將被替換成真實的值,我們稱之為:interpolations
2、FTL標志 ftl的標志有點類似html,但是它們卻是freemaker的指令語句,並不會被頁面打印輸出來,通常這些標志以#開頭
(用戶自定義的標志使用@代替#,具有更高的優先級)、
3、注釋 <#-- XXXXX -->
所有不是interpolations,ftl tag和注釋的語句都會被freemaker認為是靜態的文本,只做簡單的輸出而不會被freemaker引擎解釋執行。
二、常用指令
1、The if directive
<#if animals.python.price != 0> Pythons are not free today! </#if>
<#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today. <#else> Pythons are not cheaper than elephants today. </#if>
<#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today. <#elseif animals.elephant.price < animals.python.price> Elephants are cheaper than pythons today. <#else> Elephants and pythons cost the same today. </#if>
2、The list directive
假設我們有這樣的數據:
(root)
|
+- animals
| |
| +- (1st)
| | |
| | +- name = "mouse"
| | |
| | +- size = "small"
| | |
| | +- price = 50
| |
| +- (2nd)
| | |
| | +- name = "elephant"
| | |
| | +- size = "large"
| | |
| | +- price = 5000
| |
| +- (3rd)
| |
| +- name = "python"
| |
| +- size = "medium"
| |
| +- price = 4999
|
+- misc
|
+- fruits
|
+- (1st) = "orange"
|
+- (2nd) = "banana"
freemaker遍歷list的模板如下:
<p>We have these animals:
<table border=1>
<#list animals as animal>
<tr><td>${animal.name}<td>${animal.price} Euros
</#list>
</table>
將輸出:
<p>We have these animals:
<table border=1>
<tr><td>mouse<td>50 Euros
<tr><td>elephant<td>5000 Euros
<tr><td>python<td>4999 Euros
</table>
我們需要注意這樣一種情況:
<ul>
<#list misc.fruits as fruit>
<li>${fruit}
</#list>
</ul>
當misc.fruits就算是空的時候,程序仍然會輸出<ul></ul>,因此我們建議這樣寫:
<#list misc.fruits>
<ul>
<#items as fruit>
<li>${fruit}
</#items>
</ul>
</#list>
另外一種情景就是我們需要用一個分隔符來並列顯示我們的數組,可以寫成這樣:
<p>Fruits: <#list misc.fruits as fruit>${fruit}<#sep>, </#list>
將輸出:
<p>Fruits: orange, banana
我們用逗號來分割顯示我們的數組,只有當數組后面還有其他元素時才會顯示這個逗號,同樣的,如果我們的數組中一個元素都沒有的時候,頁面上仍然會輸出“Fruits:”,更好的寫法應該是這樣:
<p>Fruits: <#list misc.fruits as fruit>${fruit}<#sep>, <#else>None</#list>
上面說到的都是一些比較簡單的使用方法,我們還可以寫成這樣:
<p>Fruits: ${fruits?join(", ", "None")}
當然我們可以把上面說到的幾種指令用在一起:
<#list misc.fruits>
<p>Fruits:
<ul>
<#items as fruit>
<li>${fruit}<#sep> and</#sep>
</#items>
</ul>
<#else>
<p>We have no fruits.
</#list>
3、The include directive
使用include指令能將其他文件的內容插入到前文件中。
假設我們需要把版權信息放在每一個頁面的底部,我們可以將這個版權信息做成一個模板,命名成copyright_footer.html,如下:
<hr> <i> Copyright (c) 2000 <a href="http://www.acmee.com">Acmee Inc</a>, <br> All Rights Reserved. </i>
然后每個需要添加版權信息的頁面都include這個copyright_footer.html,如下:
<html> <head> <title>Test page</title> </head> <body> <h1>Test page</h1> <p>Blah blah... <#include "/copyright_footer.html"> </body> </html>
最后頁面輸出:一旦修改了這個copyright_footer.html文件,所有引用的頁面都能立即看到這些變化。
<html> <head> <title>Test page</title> </head> <body> <h1>Test page</h1> <p>Blah blah... <hr> <i> Copyright (c) 2000 <a href="http://www.acmee.com">Acmee Inc</a>, <br> All Rights Reserved. </i> </body> </html>
4、Using built-ins(使用內建函數)
- user?upper_case 把user值變成大寫 (like "JOHN DOE" instead of "John Doe")
- user?cap_first 顯示首字母大寫user值 (like "Mouse" instead of "mouse")
- user?length 顯示user的長度值 (8 for "John Doe")
- animals?size 顯示animals sequence 的元素個數
- animal.protected?string("Y", "N") 根據animal.protected這個值是true還是false,返回Y或者N
- fruits?join(", ") 把一個list用逗號分隔顯示成一串字符串
- user?starts_with("J") 如果user是以J開頭返回true,否則返回false
- 如果我們是在<#list animals as animal>遍歷中
- animal?index 獲取是從0開始的索引值
- animal?counter 獲取到的是從1開始的索引值
- animal?item_parity 根據當前元素的counter值返回是字符串“odd”或者“even”,一般用在改變奇偶行的顏色,像這樣
<td class="${animal?item_parity}Row">
5、處理缺省值
data-model有些變量是可選的(有些是不小心missing,這里說的missing,是這可能沒有這個變量,也可能是為null),為了識別出一些典型的人為錯誤,freemaker對一些缺少的變量值進行報錯,除非人為的指定這個值可以為空,下面講講幾個比較常用的方法:
1、當user值missing的時候,就會顯示成visitor
<h1>Welcome ${user!"visitor"}!</h1>
2、當user值missing的時候,整行都不顯示
<#if user??><h1>Welcome ${user}!</h1></#if>
我們需要注意這樣一種情況,當我們要判斷animals.python.price是不是等於0,我們通常會這樣寫:animals.python.price!0,但是如果animal或者Python已經missing,那么程序將報undefined variable的錯誤,為了避免這樣的情況,我們建議寫成這樣:(animals.python.price)!0,這樣,就算animal或者Python缺失,括號部分的值就會等於0,括號部分等同於(animals.python.price)??
6、Directives
前面提到,指令有預先系統定義的如<#if>,用戶自己也可以定義自己的指令,用戶自定義的指令和系統自帶指令的不同之處就是,當用戶級指令中沒有需要嵌套的內容是,必須寫成<@mydirective parameters />,就像我們html的img標簽一樣,而且用戶自定義的指令具有更高的優先級。但是無論是系統級指令還是用戶自定義指令,都必須要正確的嵌套,同時freemaker會忽略指令中大量的空格,所以你也可以寫成這樣,需要特別注意的是,並不允許在< 或者</和指令名之間插入空格。
<#list[BR]
animals as
animal
>
${animal.name} for ${animal.price} Euros
</#list >
7、expresstion
聲明:
1、字符串:"Foo" or 'Foo' or "It's \"quoted\"" or 'It\'s "quoted"' or r"C:\raw\string"
2、字符型:123.45
3、布爾值:true、false
4、序列sequence:["foo", "bar", 123.45]
5、hashes:{"name":"green mouse", "price":150}
取值:
1、頂層對象:user
2、從hashes中取值:user.name ,user["name"]
3、從sequence中取值:products[5]
4、特別變量:.main
字符串操作:
1、拼接:"Hello ${user}!" (or "Hello " + user + "!")
2、獲取字符串的某一位上的字符值:name[0]
3、分割:包含最后一位:name[0..4],不包含最后一位:name[0..<5],去頭:name[5..]
序列操作:
1、添加:users + ["guest"]
2、分割:包括最后一位products[20..29],不包括最后一位products[20..<30],去頭products[20..]
hashes操作:
添加: passwords + { "joe": "secret42" }
算數計算:(x * 1.5 + 10) / 2 - y % 100
比較: x == y, x != y, x < y, x > y, x >= y, x <= y, x lt y, x lte y, x gt y, x gte y
邏輯運算:!registered && (firstVisit || fromEurope)
方法調用: repeat("What", 3)
缺值處理:
1、默認值:name!"unknown" or (user.name)!"unknown" or name! or (user.name)!
2、空值判斷:name?? or (user.name)??
賦值運算符:=, +=, -=, *=, /=, %=, ++, --
