macro
自定义指令通过macro指令来定义。
宏是有一个变量名的模板片段。可以在模板中使用宏作为自定义指令, 这样就能进行重复性的工作。例如,创建一个宏变量hello来输出大字号的''Hello World!''。
<#macro hello>
<font size="+2">Hello World!</font>
</#macro>
macro
指令自身不输出任何内容, 它只是用来创建宏变量,所以就会有一个名为 hello的变量。在 <#macro hello>
和 </#macro>
之间的内容 (称为 宏定义体) 将会在使用该变量作为指令时执行。可以在FTL标记中通过 @
代替#
来使用自定义指令。
<@hello></@hello>
熟悉xml语法的人都了解,<hello></hello>
和 <hello/>
是相同的。所以也可以这样使用自定义指令。
<@hello/>
两种写法,最终输出的东西是一样的,都是
<font size="+2">Hello World!</font>
macro指令也可以定义参数,在宏定义体里,可以使用插值${...}也可以使用FTL标签。
我们来修改一下hello指令
<#macro hello name>
<font size="+2">Hello ${name}!</font>
</#macro>
<@hello name="zhangsan"></@hello>
<@hello name="lisi"/>
我们添加了name作为参数,模板输出结果是
<font size="+2">Hello zhangsan!</font>
<font size="+2">Hello lisi!</font>
多参数也可以,我们再次修改一下
<#macro hello name age>
<font size="+2">Hello ${name} ${age}!</font>
</#macro>
<#-- 参数顺序不影响 -->
<@hello name="zhangsan" age=11></@hello>
<@hello age=12 name="lisi"/>
输出结果是
<font size="+2">Hello zhangsan 11!</font>
<font size="+2">Hello lisi 12!</font>
这里需要注意一下,在使用自定义指令的时候,如果有参数,所有参数都必须指定,并且不能指定没有在宏定义中定义的参数。以下写法就是错误的
<@hello age=12 name="wangwu" title="test"/>
<@hello name="zhaoliu"/>
不过,我们可以给宏定义参数设置默认值,这样,有默认值的参数可以在使用中不写,如果写了参数则会替换默认值。
<#macro hello name age color="black">
<font size="+2" color=${color}>Hello ${name} ${age}!</font>
</#macro>
<#-- 参数顺序不影响 -->
<@hello name="zhangsan" age=11></@hello>
<@hello age=12 name="lisi" color='yellow'/>
最终输出结果
<font size="+2" color=black>Hello zhangsan 11!</font>
<font size="+2" color=yellow>Hello lisi 12!</font>
页面展示为
嵌套内容 <#nested>
<#nested>
指令执行位于开始和结束标记指令之间的模板代码段。
<#macro hello name age color="black">
<font size="+2" color=${color}><#nested> ${name} ${age}!</font>
</#macro>
<#-- 参数顺序不影响 -->
<@hello name="zhangsan" age=11> hello </@hello>
<@hello age=12 name="lisi"> nihao </@hello>
最终输出为
<font size="+2" color=black> hello zhangsan 11!</font>
<font size="+2" color=black> nihao lisi 12!</font>
<#nested>
会分别被 hello 和 nihao 替换。
<#nested>
指令也可以多次被调用
例如:
<#macro three>
<#nested>
<#nested>
<#nested>
</#macro>
<@three>test</@three>
最终输出结果
testtesttest
嵌套的内容可以是任意有效的FTL,包含用户自定义的其他指令
<@three><@hello age=13 name="wangwu"> test </@hello></@three>
输出结果
<font size="+2" color=black> test wangwu 13!</font>
<font size="+2" color=black> test wangwu 13!</font>
<font size="+2" color=black> test wangwu 13!</font>
给确定"循环"的循环变量传递真实值(比如重复嵌套内容)来作为 nested
指令的参数(当然参数可以是任意的表达式)。 循环变量的名称是在自定义指令的开始标记(<@...>
) 的参数后面通过分号确定的。
<#macro five>
<#nested 1>
<#nested 3>
<#nested 5>
<#nested 7>
<#nested 9>
</#macro>
<@five ; param1>
${param1} hello
</@five>
输出
1 hello
3 hello
5 hello
7 hello
9 hello