FreeMarker自定义指令就像struts2的set标签,为了好理解,也可以认为是定义一个方法,就像 js的function.在freemarker中的这个标签就是macro。在定义一个指令的时候,可以指定参数,当然也可以不指定,这里要注意了,我 这里只贴出模板文件及输出结果,freemarker的工具类请参照FreeMarker入门教程,其实也没有什么改变,直接拿过来用即可
自定义一个不带参数的指令
<#macro hello> helloworld </#macro> <@hello/> |
helloworld |
自定义一个带参数的指令
如果指令带有参数,在用这个指令的时候,参数名是不能省略的,要不会出异常
<#--对于hello这个自定义指令而言,hello后的都是参数,有两个参数一个是num一个是ok--> <#macro hello numok> <#list 1..num as n> <h1>Hello${ok}${n}</h1> </#list> </#macro> <#--<@hello/>会报错,因为hello有两个参数,在定义参数的值的时候参数名不能省略--> <@hello num=3 ok="World"/> |
<h1>HelloWorld1</h1> <h1>HelloWorld2</h1> <h1>HelloWorld3</h1> |
自定义指令的同时给参数定义了初始值,此时在调用该指令就可以省略参数,如果省略会使用默认值
<#--为repeat的两个参数定义了初始值,此时在调用该指令就可以省略参数,如果省略会使用默认值--> <#macro repeat num=10 ok="World"> <#list 1..num as n> <h1>Hello${ok}${n}</h1> </#list> </#macro> <@repeat/> |
<h1>HelloWorld1</h1> <h1>HelloWorld2</h1> |
nested标签会输出指令中的内容
<#macro test> <#--nested会输出指令中的内容--> <#nested 12 33/> <#nested 11 22/> <#nested 22 33/> </#macro>
<@test;x,y> <h1>你好啊--${x}--${y}</h1> </@test> |
<h1>你好啊--12--33</h1> <h1>你好啊--11--22</h1> <h1>你好啊--22--33</h1> |