» Articles » apache velocity tricks

apache velocity tricks

The apache velocity template engine comes with a relatively simple yet very powerful DSL, the velocity template language (VTL). The language is more powerful than you may think. This entry will show you two less known but very handy velocity tricks.

How to find out if a value is undefined?

You know the problem: if a parameter is not set and you use it in a template, you will se nothing in it’s place and this may not be what you want. You could do something like this:

#if ("$property" == "")
... do this
#else
... do that
#end

Depending on the situation, there is an easier approach which uses the fact that velocity doesn’t assign unset properties.

#set ($temp = "unknown")
#set ($temp = $property)

If ‘$property’ is not set, then $temp will keep the value ‘unknown’. Think about the possibilities!

How to build lists and maps within a template

Velocity allows to call arbitrary methods on objects. You can use this to build lists and maps very easily. There is a trick to achieve that which may look trivial, but I think it’s not commonly known.

Building a list:

## 1. initialize an empty list
#set ($list = [])
## 2. add stuff to the list
#set ($dummy = $list.add("element 1"))
#set ($dummy = $list.add("element 2"))

That’s it. You see that velocity needs to assign the return value to something, otherwise it wont do anything. As we’re not interested in the return value, we assign it to a throw away variable. Really simple.

The same goes for maps:

## 1. initialize an empty map
#set ($list = {})
## 2. add stuff to the map
#set ($dummy = $map.put("key 1", "value 1"))
#set ($dummy = $map.put("key 2", "value 2"))