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
You’re currently reading “Velocity if statement is type sensitive…,” an entry on Weblog of Michael Cutler
- Published:
- 26th July 2005 / 2:07pm
- Category:
- Jakarta Velocity
No comments
Jump to comment form | comments rss [?] | trackback uri [?]