Accessing constant values from an Apache Velocity template?

11,274

Solution 1

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.

Solution 2

Velocity can only use anything it finds in its context, after e.g.

context.put("MaxLong", Long.MAX_VALUE);

You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's Property lookup rules). The best thing to do is add the value you want to check against explicitly in your context.


Edit October 6 on second sight, it seems to be possible to access static members. See the velocity Developer guide - Support for "Static Classes" for more information. I have not tried this out, though.

Share:
11,274
fmunshi
Author by

fmunshi

I am a software engineer working at Google UK in London. All original source snippets I post on stackoverflow are dedicated to the public domain. Do with them as you see fit.

Updated on June 28, 2022

Comments

  • fmunshi
    fmunshi about 2 years

    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.