Velocity if statement is type sensitive…

Problem

I discovered that comparisons in Velocity if statements are type-sensitive the hard way.

For example, I am trying to display the 'selected' option in a html <SELECT> object. The list of possible values is $list, each is a simple 'NameValuePair' value object { String name, String value }.

The object I am editing in this form is $obj, and the field I am testing against is $obj.typeId defined as a long.

<select name='typeId' value='$!{obj.typeId}'>
#foreach ( $item in $list )
  #if ( $item.value == $obj.typeId )
    <option value='$item.value' selected='true'>$item.name</option>
  #else
    <option value='$item.value'>$item.name</option>
  #end
#end
</select>

However, the if statement on line 3 is actually comparing a String to a long which are of course never going to be equal.

Solution

The easiest work around in this case was to convert the $obj.typeId into a String before the comparison.

<select name='typeId' value='$!{obj.typeId}'>
#set ( $typeId = "$!{obj.typeId}" )
#foreach ( $item in $list )
  #if ( $item.value == $typeId )
    <option value='$item.value' selected='true'>$item.name</option>
  #else
    <option value='$item.value'>$item.name</option>
  #end
#end
</select>

Any comments / feedback welcomed ;)


About this entry