Dynamator Pure HTML for every page generation technology.
           

Creating a Dynamically Populated Choice List

This example shows how to output the elements of an indexed property as a list of selection options, and how to show the currently selected option.

Page

HTML

The first option in the list is hard-coded as blank. Because array references in Java are zero-based, the first option is indexed with value "-1". The second option in the list is marked with a class that will be used by Dynamator. The remaining options in each list are marked with class "Discard", which causes them to be removed by Dynamator.

FavoriteColor.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>Favorite Color</title>
</head>
<body>
<form>
  <p>
  Which color is your favorite?
  <select name="like">
    <option value="-1"></option>
    <option class="color">Red</option>
    <option class="Discard">Green</option>
    <option class="Discard">Blue</option>
  </select>
  <p>
  <input type="SUBMIT">
</form>
</body>
</html>

Dynamator File

FavoriteColor.dyn
<dynamator language="jsp">
  <prolog>
    <%@ page session="false" %>
    <%!
        private static final String[] colors_ = 
            new String[]
            {
                "red",
                "orange",
                "green",
                "brown",
                "slate",
            };
    %> 
    <%
        String likeInput = request.getParameter("like");
        int like = 
            ( likeInput == null || likeInput.length() == 0 )
            ? -1
            : Integer.valueOf(likeInput).intValue();
    %>
  </prolog>
  <class name="color">
    <foreach type="String[]" element="color" i="iColor">
        colors_
    </foreach>
    <attr name="value">
      <content>iColor</content>
    </attr>
    <attr name="selected">
      <if>iColor == like</if>
    </attr>
    <content>color</content>
  </class>
</dynamator>

In comparison with the previous example, the 'foreach' element has a new attribute, 'i'. The 'i' attribute names a variable to hold the iteration number, which in Java starts with 0.

The value sent by an option element in the HTTP request is the value of the 'value' attribute of the option element. Usually this is not the same as the text displayed by the option element; often, it is the offset or key of the indexed property whose name is displayed with the choice. In this example, the value is the value of the variable 'iColor'.

The '<content>' element near the end of the file causes the content of the option element to be dynamically set to the value of the variable 'color', which is the current element of the 'colors_' collection, as specified in the 'foreach' element.

JSP file

After processing with Dynamator, the resulting JSP file looks like this:

FavoriteColor.jsp (generated by Dynamator)

In Action

If you are viewing this page in a servlet engine, you can see the generated page in action.