freemarker中文手册 下载本文

? 其中参数的次序是无关的,因此下面是等价的:

<@greet color=\? 只能使用在macro指令中定义的参数,并且对所有参数赋值,所以下面的代码是错误的: <@greet person=\<@greet person=\? 可以在定义参数时指定缺省值,如:

<#macro greet person color=\> ? 这样<@greet person=\就正确了 ? 宏的参数是局部变量,只能在宏定义中有效 ? 嵌套内容

? 用户定义指令可以有嵌套内容,使用<#nested>指令执行指令开始和结束标记之间的模板

片断 ? 例子:

<#macro border>

<#nested>
这样使用该宏变量:

<@border>The bordered text 输出结果:

The bordered text
? <#nested>指令可以被多次调用,例如:

<#macro do_thrice> <#nested> <#nested> <#nested> <@do_thrice> Anything. 输出结果:

Anything. Anything. Anything. ? 嵌套内容可以是有效的FTL,下面是一个有些复杂的例子:

<@border>

    <@do_thrice>
  • <@greet person=\
输出结果:

? 宏定义中的局部变量对嵌套内容是不可见的,例如: <#macro repeat count> <#local y = \ <#list 1..count as x> ${y} ${count}/${x}: <#nested> <@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> <@repeat count=4 ; c, halfc, last> ${c}. ${halfc}<#if last> Last! 输出结果:

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 = \replace the plain var, hiding does not mater here --> 8. ${x} <#-- it still hides the plain var. --> 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. --> 5. ${x} <#-- now we see the local var. again --> 输出结果:

1. plain 2. plain 3. local