Velocity宏定义的坑与解决办法

本文介绍Velocity模板语言中宏定义的使用方法及注意事项,包括如何定义带有可选参数的宏,并通过示例展示了链接和图片宏的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Velocity宏定义的坑与解决办法

使用Velocity,当然就免不了要使用宏,或者说使用Velocity而不使用其宏,就相当于废了Velocity一半以上的武功,非常可惜的。

怎么使用Velocity的宏呢,才最大程度的发挥其作用但是又避免掉入其中的坑呢?且听悠然乱弹乱弹:

官方文档中,关于Macro是这么说的:

#macro - Allows users to define a Velocimacro (VM), a repeated segment of a VTL template, as required

Format:

# [ { ] macro [ } ] ( vmname $arg1 [ $arg2 $arg3 ... $argn ] ) [ VM VTL code... ] # [ { ] #end [ } ]

  • vmname - Name used to call the VM (#vmname)
  • $arg1 $arg2 [ ... ] - Arguments to the VM. There can be any number of arguments, but the number used at invocation must match the number specified in the definition.
  • [ VM VTL code... ] - Any valid VTL code, anything you can put into a template, can be put into a VM.

Once defined, the VM is used like any other VTL directive in a template.

#vmname( $arg1 $arg2 )

当然,上面清晰的说明了怎么写Macro,

也就是说可以写成:

1 #{macro}(macroName $varName1 $varName2)
2  
3 ##这里是模板内容
4  
5 #end
也可以写成
1 #macro(macroName $varName1 $varName2)
2  
3 ##这里是模板内容
4  
5 #end
当然参数个数可以是0..n个。

OK,确实很简单,但是上面的说法实际上只解决了如何写出满足正确语法的宏,但是实际应用当中,如果不加以约束,可能就出现非常难以查找的问题。

比如下面定义了一个超链接的宏,由于id不是每次都用得到,因此id是可选参数,可以填,也可以不填:

1 #macro(link $href $id)
2 <a href="$!href"#if($id) id="$id"#end>$bodyContent</a>
3 #end
然后,就可以如下使用了:
1 #@link("www.tinygroup.com")TinyGroup#end

上面的写法有问题么??似乎没有什么问题,即使什么参数也不传,只写下面的调用方法:

1 #@link()#end
渲染的结果也会是:
1 <a href=""></a>
OK,如此说来,真的没有啥问题。

接下来,我们又要写一个图片链接的宏,同样的由于id不是每次都需要,我们把它写成可选的:

1 #macro(image $href $id)
2 <img src="$href"#if($id) id="$id"#end>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值