天天看點

Freemarker标簽使用

a 概念 

最常用的 3 個概念 

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

hash      鍵值對的集合 

namespace 對一個ftl 檔案的引用, 利用這個名字可以通路到該ftl 檔案的資源 

b 指令 

if, else, elseif 

文法 

java代碼  

<#if condition>   

  ...   

<#elseif condition2>   

<#elseif condition3>   

...   

<#else>   

</#if>  

<#if condition> 

  ... 

<#elseif condition2> 

<#elseif condition3> 

... 

<#else> 

</#if> 

用例 

freemarker代碼  

<#if x = 1>   

  x is 1  

</#if>   

  x is not 1  

<#if x = 1> 

  x is 1 

  x is not 1 

switch, case, default, break 

<#switch value>   

  <#case refvalue1>   

         ...   

         <#break>   

  <#case refvalue2>   

  <#case refvaluen>   

  <#default>   

</#switch>  

<#switch value> 

  <#case refvalue1> 

         ... 

         <#break> 

  <#case refvalue2> 

  <#case refvaluen> 

  <#default> 

字元串 

<#switch being.size>   

  <#case "small">   

          this will be processed if it is small   

          <#break>   

  <#case "medium">   

          this will be processed if it is medium   

  <#case "large">   

          this will be processed if it is large   

          this will be processed if it is neither   

<#switch being.size> 

  <#case "small"> 

          this will be processed if it is small 

          <#break> 

  <#case "medium"> 

          this will be processed if it is medium 

  <#case "large"> 

          this will be processed if it is large 

          this will be processed if it is neither 

數字 

<#switch x>   

  <#case x = 1>   

         1  

  <#case x = 2>   

         2  

         d   

<#switch x> 

  <#case x = 1> 

         1 

  <#case x = 2> 

         2 

         d 

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

list, break 

<#list sequence as item>   

<#if item = "spring"><#break></#if>   

</#list>  

<#list sequence as item> 

<#if item = "spring"><#break></#if> 

</#list> 

關鍵字 

item_index:是list目前值的下标 

item_has_next:判斷list是否還有值 

<#assign seq = ["winter", "spring", "summer", "autumn"]>   

<#list seq as x>   

  ${x_index + 1}. ${x}<#if x_has_next>,</#if>   

<#assign seq = ["winter", "spring", "summer", "autumn"]> 

<#list seq as x> 

  ${x_index + 1}. ${x}<#if x_has_next>,</#if> 

輸出: 

      1.winter, 

      2.spring, 

      3.summer, 

      4.autumn 

include 

<#include filename>  

<#include filename> 

  或則 

<#include filename options>  

options包含兩個屬性 

encoding="gbk" 編碼格式 

parse=true 是否作為ftl文法解析,預設是true,false就是以文本方式引入.注意在ftl檔案裡布爾值都是直接指派 

的如parse=true,而不是parse="true" 

/common/copyright.ftl 包含内容 

ftl代碼  

copyright 2001-2002 ${me}   

all rights reserved.    

copyright 2001-2002 ${me} 

模闆檔案 

<#assign me = "juila smith">   

some test   

yeah   

___________________________________________________________________________   

<span><strong><span><#include "/common/copyright.ftl" encoding="gbk"></span>   

</strong>   

</span>  

<#assign me = "juila smith"> 

some test 

yeah 

___________________________________________________________________________ 

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

輸出結果: 

yeah. 

copyright 2001-2002 juila smith 

all rights reserved.  

import 

<#import path as hash>  

<#import path as hash> 類似于java裡的import,它導入檔案,然後就可以在目前檔案裡使用被導入檔案裡的宏元件

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

<#import "/libs/mylib.ftl" as my>   

<@my.copyright date="1999-2002"/>   

<#-- "my"在freemarker裡被稱作namespace -->  

<#import "/libs/mylib.ftl" as my> 

<@my.copyright date="1999-2002"/> 

<#-- "my"在freemarker裡被稱作namespace --> 

compress 

<#compress>   

</#compress>  

<#compress> 

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

escape, noescape 

<#escape identifier as expression>   

  <#noescape>...</#noescape>   

</#escape>  

<#escape identifier as expression> 

  <#noescape>...</#noescape> 

</#escape> 

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

該表達式 

<#escape x as x?html>   

  first name: ${firstname}   

  <#noescape>last name: ${lastname}</#noescape>   

  maiden name: ${maidenname}   

<#escape x as x?html> 

  first name: ${firstname} 

  <#noescape>last name: ${lastname}</#noescape> 

  maiden name: ${maidenname} 

相同表達式 

first name: ${firstname?html}   

last name: ${lastname }   

maiden name: ${maidenname?html}  

  first name: ${firstname?html} 

  last name: ${lastname } 

  maiden name: ${maidenname?html}  

assign 

<#assign name=value>   

<#-- 或則 -->   

<#assign name1=value1 name2=value2 ... namen=valuen>   

<#assign same as above... in namespacehash>   

<#assign name>   

  capture this   

</#assign>   

<#assign name in namespacehash>   

</#assign>  

<#assign name=value> 

<#-- 或則 --> 

<#assign name1=value1 name2=value2 ... namen=valuen> 

<#assign same as above... in namespacehash> 

<#assign name> 

  capture this 

</#assign> 

<#assign name in namespacehash> 

生成變量,并且給變量指派 

給seasons賦予序列值 

<#assign seasons = ["winter", "spring", "summer", "autumn"]>  

<#assign seasons = ["winter", "spring", "summer", "autumn"]> 給變量test加1 

<#assign test = test + 1>  

<#assign test = test + 1> 給my namespage 賦予一個變量bgcolor,下面可以通過my.bgcolor來通路這個變量 

<#import "/mylib.ftl" as my>   

<#assign bgcolor="red" in my>  

<#import "/mylib.ftl" as my> 

<#assign bgcolor="red" in my> 将一段輸出的文本作為變量儲存在x裡 

<#assign x>   

  <#list 1..3 as n>   

         ${n} <@mymacro />   

  </#list>   

number of words: ${x?word_list?size}   

${x}   

<#assign x>hello ${user}!</#assign>          error   

<#assign x=" hello ${user}!">         true  

<#assign x> 

  <#list 1..3 as n> 

         ${n} <@mymacro /> 

  </#list> 

number of words: ${x?word_list?size} 

${x} 

<#assign x>hello ${user}!</#assign>          error 

<#assign x=" hello ${user}!">         true 同時也支援中文指派,如: 

<#assign 文法>   

  java   

${文法}  

<#assign 文法> 

  java 

${文法} 列印輸出: 

java 

global 

<#global name=value>   

<#--或則-->   

<#global name1=value1 name2=value2 ... namen=valuen>   

<#global name>   

</#global>  

<#global name=value> 

<#--或則--> 

<#global name1=value1 name2=value2 ... namen=valuen> 

<#global name> 

     全局指派文法,利用這個文法給變量指派,那麼這個變量在所有的namespace [a1] 中是可見的, 如果這個變量被目前的assign 文法覆寫 如<#global x=2> <#assign x=1> 在目前頁面裡x=2 将被隐藏,或者通過${.global.x} 來通路 

setting 

<#setting name=value>  

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

locale 

number_format 

boolean_format 

date_format , time_format , datetime_format 

time_zone 

classic_compatible 

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

${1.2}   

<#setting locale="en_us">   

${1.2}    

${1.2} 

<#setting locale="en_us"> 

輸出 

         1,2 

         1.2 

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

macro, nested, return 

<#macro name param1 param2 ... paramn>   

  <#nested loopvar1, loopvar2, ..., loopvarn>   

  <#return>   

</#macro>  

<#macro name param1 param2 ... paramn> 

  <#nested loopvar1, loopvar2, ..., loopvarn> 

  <#return> 

</#macro> 

<#macro test foo bar="bar"[a2]  baaz=-1>   

  test text, and the params: ${foo}, ${bar}, ${baaz}   

</#macro>   

<@test foo="a" bar="b" baaz=5*5-2/>   

<@test foo="a" bar="b"/>   

<@test foo="a" baaz=5*5-2/>   

<@test foo="a"/>   

<#macro test foo bar="bar"[a2]  baaz=-1> 

  test text, and the params: ${foo}, ${bar}, ${baaz} 

<@test foo="a" bar="b" baaz=5*5-2/> 

<@test foo="a" bar="b"/> 

<@test foo="a" baaz=5*5-2/> 

  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 

定義循環輸出的宏 

<#macro list title items>   

${title?cap_first}:   

        <#list items as x>   

           *${x?cap_first}   

         </#list>   

<@list items=["mouse", "elephant", "python"] title="animals"/>  

<#macro list title items> 

${title?cap_first}: 

        <#list items as x> 

           *${x?cap_first} 

         </#list> 

      animals: 

           *mouse 

           *elephant 

           *python 

包含body 的宏 

<#macro repeat count>   

  <#list 1..count as x>   

         <#nested x, x/2, x==count>   

<@repeat count=4 ; c halfc last>   

  ${c}. ${halfc}<#if last> last!</#if>   

</@repeat>   

<#macro repeat count> 

  <#list 1..count as x> 

         <#nested x, x/2, x==count> 

<@repeat count=4 ; c halfc last> 

  ${c}. ${halfc}<#if last> last!</#if> 

  1. 0.5 

  2. 1 

  3. 1.5 

  4. 2 last! 

t, lt, rt 

freemarkder代碼  

<#t> 去掉左右空白和回車換行   

<#lt>去掉左邊空白和回車換行   

<#rt>去掉右邊空白和回車換行   

<#nt>取消上面的效果  

<#t> 去掉左右空白和回車換行 

<#lt>去掉左邊空白和回車換行 

<#rt>去掉右邊空白和回車換行 

<#nt>取消上面的效果 

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

表達式轉換類 

${expression} 計算expression 并輸出 

#{ expression } 數字計算#{ expression ;format} 安格式輸出數字format 為m 和m 

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

數字循環 

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

對浮點取整數 

${123.23?int} 輸出 123 

給變量預設值 

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

判斷對象是不是 null 

<#if mouse?exists>   

      mouse found   

<#else>  

<#if mouse?exists> 

      mouse found 

<#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字元将會被轉義,比如"<",處理後的結果是< 

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 

<#if mouse??>   

  mouse found   

  no mouse found   

creating mouse...   

<#assign mouse = "jerry">   

<#if mouse??> 

  mouse found 

  no mouse found 

creating mouse... 

<#assign mouse = "jerry"> 

(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)建立自定義模版 

<#macro greet>         

     <font size="+2">hello joe!</font>   

<#macro greet>      

     <font size="+2">hello joe!</font> 

<#assign   user="zhangsan"/> 

字元串連接配接 

${"hello  ${user}!"}   與 ${"hello " + user + "!"} 相同 

結果:hello  zhangsan 

擷取字元 

${user[0]}    ${user[4]} 

結果:z  g 

序列的連接配接和通路 

<#assign   nums=["1" , "2"] + ["3" , "4"]  /> 

${nums[0]}   結果是 1 

内置函數 

html   使用實體引用替換字元串中所有html字元,例如,使用& 替換& 

lower_case   将字元串轉化成小寫 

substring 

index_of      例如”abcdc"?index_of("bc") 将傳回1 

seq_contains    序列中是否包含指定值  ${nums?seq_contains("1")?string("yes","no")} 

seq_index_of    第一個出現的索引   ${nums?seq_index_of("1")}   結果0 

sort_by    用于散列