Freemarker 宏

本文出自链接:https://www.jianshu.com/p/5f9cf758aed8
什么是宏: 所谓宏,就是一些命令组织在一起,作为一个单独命令完成一个特定任务;
什么是Freemarker宏:在freemarker中宏是和某个变量关联的模板片断,以便在模板中通过用户定义指令使用该变量;宏可以算是Freemarker的一大特色,可以将公共的代码块进行抽取出来然后作为宏,可以减少代码量且方便维护;
宏的定义:
1.macro定义模板,然后调用直接显示

<#macro greet> 
<font size="+2">Hello World!</font> 
</#macro> 

使用:<@greet>/@greet 或 <@greet/>

结果:Hello World!

2.在macro指令中可以在宏变量之后定义参数

<#macro greet person> 
<font size="+2">Hello ${person}!</font> 
</#macro> 

使用:<@greet person=“Fred”/> and <@greet person=“Batman”/>

结果: Hello Fred! and Hello Batman!

3.macro 定义多个参数
macro可以有多个参数,参数的次序是无关的,在macro指令中只能使用定义的参数,并且必须对所有参数赋值,可以在定义参数时指定缺省值:

<#macro greet person color="black"> 
<font size="+2" color="${color}">Hello ${person}!</font> 
</#macro> 

4.自定义指令嵌套内容 <#nested>占位符

<#macro border> 
<table border=4 cellspacing=0 cellpadding=4><tr><td> 
<#nested> 
</td></tr></table> 
</#macro> 

使用:<@border>The bordered text</@border>

结果:

The bordered text
ps:<#nested>就相当于占位符:

<#nested>指令可以被多次调用:

<#macro do_thrice>
<#nested>
<#nested>
<#nested>
</#macro>
使用:
<@do_thrice>Anything.</@do_thrice>

结果:
Anything.
Anything.
Anything.
ps:<@do_thrice>中的内容就是嵌套内容

5.局部变量对嵌套内容不可见

<#macro repeat count> 
    <#local y = "test"> 
    <#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: ? ? ?
ps:其中嵌套内容中的y,x,count都是没定义的,所以取不到值
6.宏定义中使用循环变量
nested指令也可以有循环变量(循环变量的含义见下节),调用宏的时候在宏指令的参数后面,分号隔开依次列出循环变量的名字,格式如下:

<@ macro_name paramter list; loop variable list[,]>

eg:

<#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> 

ps:count是宏的参数,c,halfc,last则为循环变量,
输出结果为:

1, 0.5
2, 1
3, 1.5
4, 2 Last!
引用
循环变量和宏标记指定的不同不会有问题,如果调用时少指定了循环变量,那么多余的值不可见。调用时多指定了循环变量,多余的循环变量不会被创建:


<@repeat count=4 ; c, halfc, last> 
    ${c}. ${halfc}<#if last> Last!</#if> 
\</@repeat> 

<@repeat count=4 ; c, halfc> 
    ${c}. ${halfc} 
\</@repeat> 

<@repeat count=4> 
    Just repeat it... 
\</@repeat>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值