can Velocity set a default value for a variable when no value found in VelocityContext?

我只是一个虾纸丫 提交于 2019-12-01 17:40:18

Not easily for all variables as far as I see, I only managed to do it for some variables specifically as follows:

Template:

#if ( !$somevar )
#set ( $somevar = "mycontent" )
#end

Var is: $somevar

Result:

Var is: mycontent

Create a velocimacro in your template:

#macro(defaultValue $parm)  
#if (!$!parm || $!parm == "")  
i-like-will
#else  
$parm  
#end  
#end  

And call it like this in the same template:

#defaultValue($name)  

Check Apache Velocity - Velocity User Guide for more info on velocimacros (and velocity in general).

Google around for Velocity ReferenceInsertionEventHandler for a way to do it broadly.

Consider the DisplayTool's alt() method for individual cases (part of the VelocityTools project)

A little late to the party, but you could also perform a check when defining a variable. I had to compress this to one line to remove excess space in the output, but here is an example from one of my projects:

#set ( $qlDefault = "qlinks" )
#set ( $qlClass = "#if($sharedCtaImage.getChild('path').value != '/')$qlDefault#else$qlDefault full#end" )

Default class is defined, then I check if another, specific value is filled in to determine if I keep the default class or append an additional class. This could also work for swapping out classes as well.

For an empty default value, $!name will do. Otherwise,

#{if}($name)${name}#{else}${default_value}#{end}

See http://velocity.apache.org/engine/2.0/user-guide.html#quiet-reference-notation

Evan Haas

There are a couple things you can do short of hacking Velocity internals. Have a look at this question.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!