can Velocity set a default value for a variable wh

2019-02-22 05:07发布

问题:

Velocity just print the tag name if no value was found in VelocityContext, ie, $name in my template file, but there is no value for "name" in VelocityContext, so just "$name" was printed. I want Velocity to print a default value if there is no value for the variable, I just tried to extends AbstractCotnext and override internalGet() method, but the return value of internalGet() will be cast to Node object, I don't know how to create a new Node object in my internalGet() method, and also I think this way is very complex.

is there a simple way to set a default value (default value is just a string) ?

thanks.

回答1:

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


回答2:

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).



回答3:

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)



回答4:

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.



回答5:

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



回答6:

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



标签: velocity