4.5 Reference Miscellany

Separating Identifiers and template text

When writing templates, you might encounter situations in which it is necessary to explicitly separate a reference from the surrounding template text. In the examples above, this was done implicitly through whitespace. Additionally there is a formal notation which wraps the identifiers with curly braces:

Example 4.6. Formal notation for Velocity references


Suppose you were building an extension to your fruit shop where juices are sold. $fruit contains the name of the juice which should be sold. Using the shorthand notation would be inadequate for this task. Consider the following example:

You have selected $fruitjuice.

There is ambiguity here, and Velocity assumes that $fruitjuice, not $fruit, is the identifier that you want to use. Finding no value for $fruitjuice, it will return $fruitjuice. Using formal notation can resolve this problem.

You have selected ${fruit}juice.

Now Velocity knows that $fruit, not $fruitjuice, is the reference. Formal notation is often useful when references are directly adjacent to text in a template.

Quiet reference notation

When Velocity encounters an undefined reference, its normal behavior is to output the image of the reference. For example, suppose the following reference appears as part of a VTL template.

<input type="text" name="email" value="$email"/>

When the form initially loads, the variable reference $email has no value, but you probably prefer a blank text field to one with a value of $email. Using the quiet reference notation circumvents Velocity's normal behavior; instead of using $email in the VTL you would use $!email. So the above example would look like the following:

<input type="text" name="email" value="$!email"/>

Now when the form is initially loaded and $email still has no value, an empty string will be output instead of $email.

Formal and quiet reference notation can be used together:

<input type="text" name="email" value="$!{email}"/>

It is very easy to confuse the quiet reference notation with the boolean not-Operator. Using the not-Operator, you use !${foo}, while the quiet reference notation is $!{foo}. And yes, you will end up sometimes with !$!{foo}...