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.
You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.
Depending on what is added to the Velocity Context (MagicDraw automatically adds its element to the Velocity Context) the variable can either be a local variable or a reference to a Java object. To declare a local variable inside a template, type: $ followed by a string beginning with a letter.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.
Velocity separates Java code from the web pages, making the web site more maintainable over the long run and providing a viable alternative to Java Server Pages (JSPs) or PHP. Velocity can be used to generate web pages, SQL, PostScript and other output from templates.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With