Freemarker頁面語法

 

A 概念

最常用的 3 個概念

sequence 序列,對應java 裏的list 、數組等非鍵值對的集合

hash      鍵值對的集合

namespace 對一個ftl 文件的引用, 利用這個名字可以訪問到該ftl 文件的資源

B 指令

 

if, else, elseif

 

語法

Java代碼
  1. <#if condition>   
  2.   ...   
  3. <#elseif condition2>   
  4.   ...   
  5. <#elseif condition3>   
  6.   ...   
  7. ...   
  8. <#else>   
  9.   ...   
  10. </#if>  
<#if condition>
  ...
<#elseif condition2>
  ...
<#elseif condition3>
  ...
...
<#else>
  ...
</#if>

 

用例

 

Freemarker代碼
  1. <#if x = 1>   
  2.   x is 1  
  3. </#if>   
  4. <#if x = 1>   
  5.   x is 1  
  6. <#else>   
  7.   x is not 1  
  8. </#if>  

 

switch, case, default, break

 

語法

 

Freemarker代碼
  1. <#switch value>   
  2.   <#case refValue1>   
  3.          ...   
  4.          <#break>   
  5.   <#case refValue2>   
  6.          ...   
  7.          <#break>   
  8.   ...   
  9.   <#case refValueN>   
  10.          ...   
  11.          <#break>   
  12.   <#default>   
  13.          ...   
  14. </#switch>  

 

用例

 

Freemarker代碼
  1. <#switch being.size>   
  2.   <#case "small">   
  3.           This will be processed if it is small   
  4.           <#break>   
  5.   <#case "medium">   
  6.           This will be processed if it is medium   
  7.           <#break>   
  8.   <#case "large">   
  9.           This will be processed if it is large   
  10.           <#break>   
  11.   <#default>   
  12.           This will be processed if it is neither   
  13. </#switch>  

 

 

Freemarker代碼
  1. <#switch x>   
  2.   <#case x = 1>   
  3.          1  
  4.   <#case x = 2>   
  5.          2  
  6.   <#default>   
  7.          d   
  8. </#switch>  

 

 

list, break

 

Freemarker代碼
  1. <#list sequence as item>   
  2. ...   
  3. <#if item = "spring"><#break></#if>   
  4. ...   
  5. </#list>  

 關鍵字

item_index:是list當前值的下標

item_has_next:判斷list是否還有值

 

Freemarker代碼
  1. <#assign seq = ["winter""spring""summer""autumn"]>   
  2. <#list seq as x>   
  3.   ${x_index + 1}. ${x}<#if x_has_next>,</#if>   
  4. </#list>  

 

輸出:

      1.winter,

      2.spring,

      3.summer,

      4.autumn

 

include

 

Freemarker代碼
  1. <#include filename>  

  或則

Java代碼
  1. <#include filename options>  
<#include filename options>

 

options包含兩個屬性

encoding="GBK" 編碼格式

parse=true 是否作爲ftl語法解析,默認是true,false就是以文本方式引入.注意在ftl文件里布爾值都是直接賦值
的如parse=true,而不是parse="true"

 

Ftl代碼
  1. Copyright 2001-2002 ${me}   
  2.   
  3. All rights reserved.    

 

 

Java代碼
  1. <#assign me = "Juila Smith">   
  2.   
  3. Some test   
  4.   
  5. Yeah   
  6. ___________________________________________________________________________   
  7.   
  8. <SPAN><STRONG><SPAN><#include "/common/copyright.ftl" encoding="GBK"></SPAN>   
  9.   
  10.   
  11.   
  12.   
  13. </STRONG>   
  14.   
  15.   
  16. </SPAN>  
<#assign me = "Juila Smith">

Some test

Yeah
___________________________________________________________________________

<#include "/common/copyright.ftl" encoding="GBK">










 

Import

 

Freemarker代碼
<#import path as hash>  

 類似於java裏的import,它導入文件,然後就可以在當前文件裏使用被導入文件裏的宏組件

 

Freemarker代碼
  1. <#import "/libs/mylib.ftl" as my>   
  2.   
  3. <@my.copyright date="1999-2002"/>   
  4.   
  5. <#-- "my"在freemarker裏被稱作namespace -->  

 

 

compress

 

Freemarker代碼
  1. <#compress>   
  2.   ...   
  3. </#compress>  

 

 

escape, noescape

 

Freemarker代碼
  1. <#escape identifier as expression>   
  2.   ...   
  3.   <#noescape>...</#noescape>   
  4.   ...   
  5. </#escape>  

 

Freemarker代碼
  1. <#escape x as x?html>   
  2.   First name: ${firstName}   
  3.   <#noescape>Last name: ${lastName}</#noescape>   
  4.   Maiden name: ${maidenName}   
  5. </#escape>  

 

Ftl代碼
  1. First name: ${firstName?html}   
  2. Last name: ${lastName }   
  3. Maiden name: ${maidenName?html}  

 

 

assign

 

Freemarker代碼
  1. <#assign name=value>   
  2.   
  3. <#-- 或則 -->   
  4.   
  5. <#assign name1=value1 name2=value2 ... nameN=valueN>   
  6.   
  7. <#-- 或則 -->   
  8.   
  9. <#assign same as above... in namespacehash>   
  10.   
  11. <#-- 或則 -->   
  12.   
  13. <#assign name>   
  14.   capture this   
  15. </#assign>   
  16.   
  17. <#-- 或則 -->   
  18.   
  19. <#assign name in namespacehash>   
  20.   capture this   
  21. </#assign>  

 

 

Ftl代碼
  1. <#assign seasons = ["winter""spring""summer""autumn"]>  

 給變量test加1

Ftl代碼
  1. <#assign test = test + 1>  

 給my namespage 賦予一個變量bgColor,下面可以通過my.bgColor來訪問這個變量

Ftl代碼
  1. <#import "/mylib.ftl" as my>   
  2.   
  3. <#assign bgColor="red" in my>  

 將一段輸出的文本作爲變量保存在x裏

Ftl代碼
  1. <#assign x>   
  2.   <#list 1..3 as n>   
  3.          ${n} <@myMacro />   
  4.   </#list>   
  5. </#assign>   
  6.   
  7. Number of words: ${x?word_list?size}   
  8.   
  9. ${x}   
  10.   
  11. <#assign x>Hello ${user}!</#assign>          error   
  12.   
  13. <#assign x=" Hello ${user}!">         true  

 同時也支持中文賦值,如:

Ftl代碼
  1. <#assign 語法>   
  2.   java   
  3. </#assign>   
  4.   
  5. ${語法}  

 打印輸出:

java


 

global

 

Freemarker代碼
  1. <#global name=value>   
  2.   
  3. <#--或則-->   
  4.   
  5. <#global name1=value1 name2=value2 ... nameN=valueN>   
  6.   
  7. <#--或則-->   
  8.   
  9. <#global name>   
  10.   capture this   
  11. </#global>  

 

 

setting

 

Freemarker代碼
  1. <#setting name=value>  

 

 

Ftl代碼
  1. ${1.2}   
  2.   
  3. <#setting locale="en_US">   
  4.   
  5. ${1.2}    

 

 

macro, nested, return

 

Freemarker代碼
  1. <#macro name param1 param2 ... paramN>   
  2.   ...   
  3.   <#nested loopvar1, loopvar2, ..., loopvarN>   
  4.   ...   
  5.   <#return>   
  6.   ...   
  7. </#macro>  

 

Ftl代碼
  1. <#macro test foo bar="Bar"[A2]  baaz=-1>   
  2.   Test text, and the params: ${foo}, ${bar}, ${baaz}   
  3. </#macro>   
  4.   
  5. <@test foo="a" bar="b" baaz=5*5-2/>   
  6.   
  7. <@test foo="a" bar="b"/>   
  8.   
  9. <@test foo="a" baaz=5*5-2/>   
  10.   
  11. <@test foo="a"/>   

 

 

Ftl代碼
  1. <#macro list title items>   
  2. ${title?cap_first}:   
  3.         <#list items as x>   
  4.            *${x?cap_first}   
  5.   
  6.          </#list>   
  7. </#macro>   
  8.   
  9. <@list items=["mouse""elephant""python"] title="Animals"/>  

 

輸出結果:
      Animals:
           *Mouse
           *Elephant
           *Python

 

 

Ftl代碼
  1. <#macro repeat count>   
  2.   <#list 1..count as x>   
  3.          <#nested x, x/2, x==count>   
  4.   </#list>   
  5. </#macro>   
  6.   
  7. <@repeat count=4 ; c halfc last>   
  8.   ${c}. ${halfc}<#if last> Last!</#if>   
  9. </@repeat>   

 

 

t, lt, rt

 

Freemarkder代碼
  1. <#t> 去掉左右空白和回車換行   
  2.   
  3. <#lt>去掉左邊空白和回車換行   
  4.   
  5. <#rt>去掉右邊空白和回車換行   
  6.   
  7. <#nt>取消上面的效果  

 

Ftl代碼
  1. <#if mouse?exists>   
  2.       Mouse found   
  3. <#else>  

 也可以直接${mouse?if_exists})輸出布爾形

 

--------------------------------------------

(1)解決輸出中文亂碼問題:

     freemarker亂碼的原因:

  • 沒有使用正確的編碼格式讀取模版文件,表現爲模版中的中文爲亂碼

解決方法:在classpath上放置一個文件freemarker.properties,在裏面寫上模版文件的編碼方式,比如

default_encoding=UTF-8
locale=zh_CN

注意:eclipse中除了xml文件、java文件外,默認的文件格式iso8859-1

  • 數據插入模版時,沒有使用正確的編碼,表現出模版中的新插入數據爲亂碼

解決方法:在result的配置中,指定charset,s2的FreemarkerResult.java會將charset傳遞freemarker

<action name="ListPersons" class="ListPersons">

<result type="freemarker">

    <param name="location">/pages/Person/view.ftl</param>

    <param name="contentType"> text/html;charset=UTF-8

</param>

</result>

</action>

(2)提高freemarker的性能

在freemarker.properties中設置:

template_update_delay=60000

避免每次請求都重新載入模版,即充分利用cached的模版

(3)儘量使用freemarker本身的提供的tag,使用S2 tags 的標籤會在性能上有所損失

 

(4)freemarker的標籤種類:

  • ${..}:FreeMarker will replace it in the output with the actual value of the thing in the curly brackets. They are called interpolation s.
  • # ,代表是FTL tags(FreeMarker Template Language tags) ,hey are instructions to FreeMarker and will not be printed to the output
    • <#if ...></#if>
    • <#list totalList as elementObject>...</#list>
  • @ ,代表用戶自定義的標籤
  • <#-- --> 註釋標籤,注意不是<!-- -->

(5)一些特殊的指令:  

  • r代表原樣輸出:${r"C:/foo/bar"}
  • <#list ["winter", "spring", "summer", "autumn"] as x>${x}</#list>
  • ?引出內置指令
    • String處理指令:
      • html:特殊的html字符將會被轉義,比如"<",處理後的結果是&lt;
      • cap_first lower_case upper_case
      • trim :除去字符串前後的空格
    • sequences處理指令
      • size :返回sequences的大小
    • numbers處理指令
      • int:number的整數部分,(e.g. -1.9?int is -1)

(6)對於null,或者miss value,freemarker會報錯

  •   ?exists:舊版本的用法
  • !:default value operator,語法結構爲: unsafe_expr !default_expr,比如 ${mouse!"No mouse."} 當mouse不存在時,返回default value;
    • (product.color)!"red" 這種方式,能夠處理product或者color爲miss value的情況;
    • 而product.color!"red"將只處理color爲miss value的情況
  • ??: Missing value test operator ,測試是否爲missing value
    • unsafe_expr ?? :product.color??將只測試color是否爲null
    • (unsafe_expr )??:(product.color)??將測試product和color是否存在null
Ftl代碼
  1. <#if mouse??>   
  2.   Mouse found   
  3. <#else>   
  4.   No mouse found   
  5. </#if>   
  6. Creating mouse...   
  7. <#assign mouse = "Jerry">   
  8. <#if mouse??>   
  9.   Mouse found   
  10.   
  11. <#else>   
  12.   No mouse found   
  13. </#if>  

 

(7)模版值插入方式 (interpolation)

  • 通用方式 Universal interpolations): ${expression }

 

  • 對於字符串:只是簡單輸出
  • 對於數值,會自動根據local確定格式,稱爲human audience,否則稱爲computer audience,可以"?c", 比如, <a href="/shop/details?id=${product.id ?c }">Details...</a>,因此這裏的id是給瀏覽器使用的,不需要進行格式化,注意?c只對數值有效
  • 對於日期,會使用默認的日期格式轉換,因此需要事先設置好默認的轉換格式,包括date_format , time_format atetime_format
  • 對於布爾值,不能輸出,會報錯並停止模版的執行,比如${a = 2} 會出錯,但是可以 string built-in來進行轉換

數值處理,具體參考:Built-ins for numbers

    http://freemarker.org/docs/ref_builtins_number.html#ref_builtin_string_for_number

    數值處理的例子:
   
    <#setting number_format="currency"/>
    <#assign answer=42/>
    ${answer}
    ${answer?string} <#-- the same as ${answer} -->
    ${answer?string.number}
    ${answer?string.currency}
    ${answer?string.percent}

    除了使用內置的formate,可以使用任何用Java decimal number format syntax 書寫的formate,比如

    <#setting number_format="0.###E0"/>

    <#setting number_format="0"/>

    <#setting number_format="#"/>
    ${1234}
    ${12345?string("0.####E0")}

    更加方便的格式:

    <#setting locale="en_US">
    US people writes:        ${12345678?string(",##0.00")}

    <#setting locale="hu">
    Hungarian people writes: ${12345678?string(",##0.00")}

    

    日期處理,參考Built-ins for dates

    http://freemarker.org/docs/ref_builtins_date.html#ref_builtin_string_for_date

    日期處理的例子:

  •     ${openingTime?string.short}
  •     ${openingTime?string.medium}
  •     ${openingTime?string.long}
  •     ${openingTime?string.full}
  •     ${nextDiscountDay?string.short}
  •     ${nextDiscountDay?string.medium}
  •     ${nextDiscountDay?string.long}
  •     ${nextDiscountDay?string.full}
  •     ${lastUpdated?string.short}
  •     ${lastUpdated?string.medium}
  •     ${lastUpdated?string.long}
  •     ${lastUpdated?string.full}

 

注意:

    由於java語言中的Date類型的不足,freemarker不能根據Date變量判斷出變量包含的部分(日期、時間還是全部),在這種情況下,freemarker

    不能正確顯示出${lastUpdated?string.short} 或者 simply ${lastUpdated},因此,可以通過?date, ?time and ?datetime built-ins

    來幫助freemarker來進行判斷,比如${lastUpdated?datetime?string.short}

    除了使用內置的日期轉換格式外,可以自己指定日期的格式,使用的是Java date format syntax,比如:

  •     ${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')'")}

    數值專用方式 Numerical interpolations):#{expression } or #{expression ; format },這是數值專用的輸出方式,但是 最好使用通用方式的string built-in或者number_format 來完成轉換,Numerical interpolations方式將會被停用

(8)創建自定義模版

Ftl代碼
  1. <#macro greet>         
  2.      <font size="+2">Hello Joe!</font>   
  3. </#macro>  

C 一些常用方法或注意事項

表達式轉換類

${expression} 計算expression 並輸出

#{ expression } 數字計算#{ expression ;format} 安格式輸出數字formatMm

M 表示小數點後最多的位數,m 表示小數點後最少的位數如#{121.2322;m2M2} 輸出121.23

數字循環

1..5 表示從15 ,原型number..number

對浮點取整數

${123.23?int} 輸出 123

給變量默認值

${var?default("hello world")?html} 如果var is null 那麼將會被hello world 替代

判斷對象是不是 null

語法

輸出

  1. 0.5
  2. 1
  3. 1.5

  4. 2 Last!

包含body 的宏

輸出

  Test text, and the params: a, b, 23
  Test text, and the params: a, b, -1
  Test text, and the params: a, Bar, 23

  Test text, and the params: a, Bar, -1

 

定義循環輸出的宏

用例

語法

輸出

         1,2

         1.2

因爲匈牙利是採用", "作爲十進制的分隔符,美國是用". "

用來設置整個系統的一個環境

locale

number_format

boolean_format

date_format , time_format , datetime_format

time_zone

classic_compatible

用例

假如當前是匈牙利的設置,然後修改成美國

語法

     全局賦值語法,利用這個語法給變量賦值,那麼這個變量在所有的namespace [A1] 中是可見的, 如果這個變量被當前的assign 語法覆蓋 如<#global x=2> <#assign x=1> 在當前頁面裏x=2 將被隱藏,或者通過${.global.x} 來訪問

語法

用例

生成變量,並且給變量賦值

給seasons賦予序列值

語法

相同表達式

用例

      主要使用在相似的字符串變量輸出,比如某一個模塊的所有字符串輸出都必須是html安全的,這個時候就可以使用

該表達式

語法

用來壓縮空白空間和空白的行

語法

用例

假設mylib.ftl 裏定義了宏copyright 那麼我們在其他模板頁面裏可以這樣使用

語法

 


輸出結果:

Some test

Yeah.

Copyright 2001-2002 Juila Smith

All rights reserved. 

 

模板文件

 

用例

/common/copyright.ftl 包含內容

語法

用例

語法

如果x=1 輸出 1 2, x=2 輸出 2, x=3 輸出d

數字

字符串

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章