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.

CODE:
  1. <select name='typeId' value='$!{obj.typeId}'>
  2. #foreach ( $item in $list )
  3.   #if ( $item.value == $obj.typeId )
  4.     <option value='$item.value' selected='true'>$item.name</option>
  5.   #else
  6.     <option value='$item.value'>$item.name</option>
  7.   #end
  8. #end
  9. </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.

CODE:
  1. <select name='typeId' value='$!{obj.typeId}'>
  2. #set ( $typeId = "$!{obj.typeId}" )
  3. #foreach ( $item in $list )
  4.   #if ( $item.value == $typeId )
  5.     <option value='$item.value' selected='true'>$item.name</option>
  6.   #else
  7.     <option value='$item.value'>$item.name</option>
  8.   #end
  9. #end
  10. </select>

Any comments / feedback welcomed ;)

No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required, but not displayed publically)