Accessing constant values from an Apache Velocity template?

Simon Nickerson picture Simon Nickerson · Sep 29, 2008 · Viewed 10.9k times · Source

Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?

I would like to be able to write something like this:

#if ($a lt Long.MAX_VALUE)

but this is apparently not the right syntax.

Answer

Nathan Bubna picture Nathan Bubna · Oct 18, 2008

There are a number of ways.

1) You can put the values directly in the context.

2) You can use the FieldMethodizer to make all public static fields in a class available.

3) You can use a custom Uberspect implementation that includes public static fields in the lookup order.

4) You can use the FieldTool from VelocityTools.

I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.