如:
<#macro greet person color>
使用时:
<@greet color=\正确
<@greet person=\错误,color没有赋值,此时,如果在定义宏时为color定义缺省值<#macro greet person color=\这样的话,这个使用方法就是正确的。
<@greet color=\错误,宏greet定义中未指定bgcolor这个参数
2、嵌套内容:
2-1、自定义指令可以有嵌套内容,使用<#nested>指令,执行自定义指令开始和结束标记之间的模板片段。例如:
<#macro greet> <#nested> #macro>
<@greet>hello Emma!@greet> 输出为 hello Emma!
2-2、<#nested>指令可以被多次调用,例如 <#macro greet> <#nested> <#nested> <#nested>
<#nested>
#macro>
<@greet>hello Emma!@greet> 输出为 hello Emma! hello Emma! hello Emma! hello Emma!
2-3、嵌套的内容可以是有效的FTL,例如: <#macro welcome> <#nested> #macro>
<#macro greet person color=\
<@welcome>
<@greet person=\<@greet person=\<@greet person=\@welcome> 输出为:
2-4、宏定义中的局部变量对嵌套内容是不可见的,例如: <#macro repeat count> <#local y=\ <#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:??? 2-5、在宏定义中使用循环变量,通常用来重复嵌套内容,基本用法为:作为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. 2last! 注意:指定循环变量的数目和用户定义指令开始标记指定的不同不会有问题 调用时,少指定循环变量,多指定的值会不见 调用时,多指定循环变量,多余的循环变量不会被创建 二、在模板中定义变量 1、在模板中定义的变量有三种类型 1-1、plain变量:可以在模板的任何地方访问,包括使用include指令插入的模板,使用assign指令创建和替换。 1-2、局部变量:在宏定义体中有效,使用local指令创建和替换。 1-3、循环变量:只能存在于指令的嵌套内容,由指令(如list)自动创建。 注意: 1)、宏的参数是局部变量,不是循环变量。 2)、局部变量隐藏同名的plain变量 3)、循环变量隐藏同名的plain变量和局部变量。 例如: <#assign x=\1. ${x} <#-- plain --> <@test /> 6. ${x} <#list [\7. ${x} <#-- loop --> <#assign x=\8. ${x} <#-- loop --> #list> 9. ${x} <#-- plain2 --> <#macro test> 2. ${x} <#-- plain --> <#local x=\3. ${x} <#-- local --> <#list [\4. ${x} <#-- loop --> #list> 5. ${x} <#-- local --> #macro> 4)、内部循环变量隐藏同名的外部循环变量 <#list [\${x} <#-- loop1 --> <#list [\${x} <#-- loop2 --> <#list [\${x} <#-- loop3 --> #list> ${x} <#-- loop2 --> #list>