本文出自链接:https://www.jianshu.com/p/5f9cf758aed8
什么是宏: 所谓宏,就是一些命令组织在一起,作为一个单独命令完成一个特定任务;
什么是Freemarker宏:在freemarker中宏是和某个变量关联的模板片断,以便在模板中通过用户定义指令使用该变量;宏可以算是Freemarker的一大特色,可以将公共的代码块进行抽取出来然后作为宏,可以减少代码量且方便维护;
宏的定义:
1.macro定义模板,然后调用直接显示
<#macro greet>
<font size="+2">Hello World!</font>
</#macro>
使用:<@greet>/@greet 或 <@greet/>
结果:Hello World!
2.在macro指令中可以在宏变量之后定义参数
<#macro greet person>
<font size="+2">Hello ${person}!</font>
</#macro>
使用:<@greet person=“Fred”/> and <@greet person=“Batman”/>
结果: Hello Fred! and Hello Batman!
3.macro 定义多个参数
macro可以有多个参数,参数的次序是无关的,在macro指令中只能使用定义的参数,并且必须对所有参数赋值,可以在定义参数时指定缺省值:
<#macro greet person color="black">
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
4.自定义指令嵌套内容 <#nested>占位符
<#macro border>
<table border=4 cellspacing=0 cellpadding=4><tr><td>
<#nested>
</td></tr></table>
</#macro>
使用:<@border>The bordered text</@border>
结果:
The bordered text |
<#nested>指令可以被多次调用:
<#macro do_thrice>
<#nested>
<#nested>
<#nested>
</#macro>
使用:
<@do_thrice>Anything.</@do_thrice>
结果:
Anything.
Anything.
Anything.
ps:<@do_thrice>中的内容就是嵌套内容
5.局部变量对嵌套内容不可见
<#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>
输出结果
test 3/1: ? ? ?
test 3/2: ? ? ?
test 3/3: ? ? ?
ps:其中嵌套内容中的y,x,count都是没定义的,所以取不到值
6.宏定义中使用循环变量
nested指令也可以有循环变量(循环变量的含义见下节),调用宏的时候在宏指令的参数后面,分号隔开依次列出循环变量的名字,格式如下:
<@ 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是宏的参数,c,halfc,last则为循环变量,
输出结果为:
1, 0.5
2, 1
3, 1.5
4, 2 Last!
引用
循环变量和宏标记指定的不同不会有问题,如果调用时少指定了循环变量,那么多余的值不可见。调用时多指定了循环变量,多余的循环变量不会被创建:
<@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>