10

all. I need to use java 5 enum in velocity template, so that I could write something like

public enum Level{
    INFO, ERROR;
}

Velocity template:

#if($var == Level.INFO)
...
#else
...
#end

How can it be done? Thanks in advance.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Depending on what your if .. else .. actually do. Also, whether this is only 1 kind or many different operations. http://stackoverflow.com/questions/859563/java-enums-and-switch-statements-the-default-case might be helpful. – bryantsai Jul 10 '09 at 06:10

3 Answers3

19

Actually, instead of toString() method it would be better to use name(), as it returns exactly the value of enum and is final hence can't be overriden in future. So in velocity you can use something like

#if($var.name() == "INFO")
Maksym Govorischev
  • 764
  • 2
  • 5
  • 12
7

As of Velocity 1.5, if the two items being compared with == are of different classes, it automatically does a toString() on both. So try

#if($var == "INFO")
Will Glass
  • 4,800
  • 6
  • 34
  • 44
3

Not pretty, but one workaround would be to (manually) place the enum constants that you need into the Velocity context.

request.setAttribute('level_info', Level.INFO);
request.setAttribute('level_error', Level.ERROR);

Then you could say

#if ($var == $level_info)

Maybe easier: Just use the toString() of your enum instance

#if ("$var" == 'INFO') 
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • @bryantsai: The second version will also be true if $var holds some other object that prints as INFO, such as a String. Unlikely that this is going to be a problem, though. – Thilo Jul 10 '09 at 06:42