You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@velocity.apache.org by Mark Hawkes <ha...@onetel.com> on 2005/01/07 06:24:01 UTC
Default Reference Values
In Perl, using HTML::Template, I can specify a default value in case the
template variable remains unassigned, like so:
<h1><tmpl_var name="greeting" default="hello"></h1>
How can I emulate this in VTL, so that if there's no value for
"greeting" in the context it displays "hello" instead of just "$greeting"...
<h1>$greeting</h1>
Many TIA,
Marco
---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org
Re: Default Reference Values
Posted by Simon Christian <si...@stoutstick.com>.
Hi Marco,
There are two simple ways to do this: using a macro or a tool that does
the same job e.g.
#* macro example *#
// define the macro
// you may want to play with this depending on whether you would accept
// an empty string as the value
#macro( valueOrDefault $_value $_default )
#if( $_value ) $_value #else $_default #end
#end
#valueOrDefault( $greeting "hello" )
#* tool example *#
// create a tool class
public class MyTool
{
public String valueOrDefault( String value, String default )
{
// this behaviour is slightly different to the macro as it
// won't accept the empty string
if( value != null && value.length() > 0 )
{
return value;
}
else if( default != null && default.length() > 0 )
{
return default;
}
else
{
return null;
}
}
}
// put it into your context somewhere
ctx.put( "mytool", new MyTool() );
// and use it
$mytool.valueOrDefault( "$greeting", "hello" )
Personally I prefer the macro..
hth,
- simon
Mark Hawkes wrote:
> In Perl, using HTML::Template, I can specify a default value in case the
> template variable remains unassigned, like so:
>
> <h1><tmpl_var name="greeting" default="hello"></h1>
>
> How can I emulate this in VTL, so that if there's no value for
> "greeting" in the context it displays "hello" instead of just
> "$greeting"...
>
> <h1>$greeting</h1>
>
> Many TIA,
> Marco
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: velocity-user-help@jakarta.apache.org
>
---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org