what
宏是在模板中使用macro指令定義
宏是和某個變量關(guān)聯(lián)的模板片斷,以便在模板中通過用戶定義指令使用該變量,
why
有人說用freemarker,但沒有用到它的宏(macro),就=?jīng)]有真正用過freemarker。說的就是宏是freemarker的一大特色。
how
注意點:調(diào)用宏時,與使用FreeMarker的其他指令類似,只是使用@替代FTL標(biāo)記中的#。
1.macro定義模板,然后調(diào)用直接顯示
<#macro greet>
<font size="+2">Hello World!</font>
</#macro>
使用:<@greet>/@greet 或 <@greet/>
結(jié)果:<font size="+2">Hello World!</font>
2.在macro指令中可以在宏變量之后定義參數(shù)
<#macro greet person>
<font size="+2">Hello ${person}!</font>
</#macro>
使用:<@greet person="Fred"/> and <@greet person="Batman"/>
結(jié)果: <font size="+2">Hello Fred!</font> and <font size="+2">Hello Batman!</font>
3.macro 定義多個參數(shù)
macro可以有多個參數(shù),參數(shù)的次序是無關(guān)的,在macro指令中只能使用定義的參數(shù),并且必須對所有參數(shù)賦值,可以在定義參數(shù)時指定缺省值:
<#macro greet person color="black">
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
4.自定義指令嵌套內(nèi)容 <#nested>
<#macro border>
<table border=4 cellspacing=0 cellpadding=4><tr><td>
<#nested>
</td></tr></table>
</#macro>
使用:<@border>The bordered text/@border
結(jié)果:
<table border=4 cellspacing=0 cellpadding=4>
<tr><td>The bordered text
</td></tr></table>
ps:<#nested>就相當(dāng)于占位符
<#nested>指令可以被多次調(diào)用:
<#macro do_thrice>
<#nested>
<#nested>
<#nested>
</#macro>
使用:
<@do_thrice>Anything.</@do_thrice>
結(jié)果:
Anything.
Anything.
Anything.
ps:<@do_thrice>中的內(nèi)容就是嵌套內(nèi)容
5.局部變量對嵌套內(nèi)容不可見
<#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>
輸出結(jié)果
- test 3/1: ? ? ?
- test 3/2: ? ? ?
- test 3/3: ? ? ?
ps:其中嵌套內(nèi)容中的y,x,count都是沒定義的,所以取不到值
6.宏定義中使用循環(huán)變量
nested指令也可以有循環(huán)變量(循環(huán)變量的含義見下節(jié)),調(diào)用宏的時候在宏指令的參數(shù)后面,分號隔開依次列出循環(huán)變量的名字,格式如下:
<@ macro_name paramter list; loop variable list[,]>
eg:
<#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>
ps:count是宏的參數(shù),c,halfc,last則為循環(huán)變量,
輸出結(jié)果為:
- 1, 0.5
- 2, 1
- 3, 1.5
- 4, 2 Last!
引用
循環(huán)變量和宏標(biāo)記指定的不同不會有問題,如果調(diào)用時少指定了循環(huán)變量,那么多余的值不可見。調(diào)用時多指定了循環(huán)變量,多余的循環(huán)變量不會被創(chuàng)建:
<@repeat count=4 ; c, halfc, last>
${c}. ${halfc}<#if last> Last!</#if>
</@repeat>
<@repeat count=4 ; c, halfc>
${c}. ${halfc}
</@repeat>
<@repeat count=4>
Just repeat it...
</@repeat>