Velocimacro – Generate a HTML Select box and its Options

A quick and simple Velocimacro to generate HTML Select boxes and its Options; automatically selects the correct option based on the value given.

You can place this #macro anywhere in your Velocity templates but I used my global VM_global_library.vm file.

Code

CODE:
  1. #macro( generateSelectBox $name $options $value )
  2. <select name='$name' value='$value'>
  3. #foreach ( $option in $options )
  4.   #set( $selected = "" )
  5.   #if ( $option == $value )
  6.     #set( $selected = "selected='true'" )
  7.   #end
  8.   <option value='$option' $selected>$option</option>
  9. #end
  10. </select>
  11. #end

Example Usage

CODE:
  1. #generateSelectBox( "enabled" ["Y","N"] $form.enabled )

The resulting HTML:

CODE:
  1. <select name='enabled' value='N'>
  2.   <option value='Y'>Y</option>
  3.   <option value='N' selected='true'>N</option>
  4. </select>

Addendum

11th November 2005 : Thanks to MATT for pointing out the FreeMarker template engine as a promising replacement for Velocity. ;)