? 宏和变换器变量是两种不同类型的用户定义指令,它们之间的区别是宏
是在模板中使用macro指令定义,而变换器是在模板外由程序定义,这里只介绍宏 ? 基本用法
? 宏是和某个变量关联的模板片断,以便在模板中通过用户定义指令使用
该变量,下面是一个例子:
<#macro greet>
? 作为用户定义指令使用宏变量时,使用@替代FTL标记中的#
<@greet>@greet>
? 如果没有体内容,也可以使用:
<@greet/>
? 参数
? 在macro指令中可以在宏变量之后定义参数,如:
<#macro greet person>
#macro>
? 可以这样使用这个宏变量:
<@greet person=\/> and <@greet person=\/>
输出结果是:
and
? 宏的参数是FTL表达式,所以下面的代码具有不同的意思:
<@greet person=Fred/>
? 这意味着将Fred变量的值传给person参数,该值不仅是字符串,还可
以是其它类型,甚至是复杂的表达式 ? 宏可以有多参数,下面是一个例子:
<#macro greet person color>
#macro>
? 可以这样使用该宏变量:
<@greet person=\
? 其中参数的次序是无关的,因此下面是等价的:
<@greet color=\
? 只能使用在macro指令中定义的参数,并且对所有参数赋值,所以下面
的代码是错误的:
<@greet person=\ <@greet person=\
? 可以在定义参数时指定缺省值,如:
<#macro greet person color=\>
? 这样<@greet person=\就正确了 ? 宏的参数是局部变量,只能在宏定义中有效 ? 嵌套内容
? 用户定义指令可以有嵌套内容,使用<#nested>指令执行指令开始和结
束标记之间的模板片断 ? 例子:
<#macro border>
<#nested> #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.
? 嵌套内容可以是有效的FTL,下面是一个有些复杂的例子:
<@border> <@do_thrice>
<@greet person=\ @do_thrice> @border>
输出结果:
? 宏定义中的局部变量对嵌套内容是不可见的,例如: <#macro repeat count> <#local y = \ <#list 1..count as x> ${y} ${count}/${x}: <#nested> #list> #macro> <@repeat count=3>${y?default(\${count?default(\ 输出结果: test 3/1: ? ? ? test 3/2: ? ? ? test 3/3: ? ? ? ? ? 在宏定义中使用循环变量 ? 用户定义指令可以有循环变量,通常用于重复嵌套内容,基本用法是: 作为nested指令的参数传递循环变量的实际值,而在调用用户定义指令时,在<@…>开始标记的参数后面指定循环变量的名字 ? 例子: <#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> 输出结果: 1. 0.5 2. 1 3. 1.5 4. 2 Last! ? 指定的循环变量的数目和用户定义指令开始标记指定的不同不会有问 题 ? 调用时少指定循环变量,则多指定的值不可见 ? 调用时多指定循环变量,多余的循环变量不会被创建 (2)在模板中定义变量 ? 在模板中定义的变量有三种类型: ? plain变量:可以在模板的任何地方访问,包括使用include指令插入 的模板,使用assign指令创建和替换 ? 局部变量:在宏定义体中有效,使用local指令创建和替换 ? 循环变量:只能存在于指令的嵌套内容,由指令(如list)自动创建; 宏的参数是局部变量,而不是循环变量 ? 局部变量隐藏(而不是覆盖)同名的plain变量;循环变量隐藏同名的局 部变量和plain变量,下面是一个例子: <#assign x = \ 1. ${x} <#-- we see the plain var. here --> <@test/> 6. ${x} <#-- the value of plain var. was not changed --> <#list [\ 7. ${x} <#-- now the loop var. hides the plain var. --> <#assign x = \--> 8. ${x} <#-- it still hides the plain var. --> #list> 9. ${x} <#-- the new value of plain var. --> <#macro test> 2. ${x} <#-- we still see the plain var. here --> <#local x = \ 3. ${x} <#-- now the local var. hides it --> <#list [\ 4. ${x} <#-- now the loop var. hides the local var. --> #list> 5. ${x} <#-- now we see the local var. again --> #macro> 输出结果: 1. plain 2. plain 3. local 4. loop 5. local 6. plain