9.7. Writing Templates with Conditionals and Loops

Problem

Your template needs to iterate over a list of objects and highlight objects if a specific property meets a certain criteria.

Solution

Use a Velocity template with the #foreach and #if directives. The following Velocity template uses a #foreach to loop through a List of Airport beans and an #if to check for the location of an airport relative to the supplied $countryCode:

The World's Busiest Airports

<table>
  <tr>
    <td>Rank</td><td>Code</td><td>Name</td><td>Passengers</td>
    <td>${countryCode} Domestic</td>
  </tr>
  #foreach( $airport in $airports )
    <tr>
      <td>$velocityCount</td>
      <td>$airport.code</td>
      <td>$airport.name</td>
      <td>$airport.passengers</td>
      #if( $airport.countryCode == $countryCode )
        <td>Y</td>
      #else
        <td>N</td>
      #end
    </tr>
  #end
</table>

To render this template, a List of Airport objects and a countryCode String is created and put into a VelocityContext. The $countryCode reference is used to test the countryCode property of every Airport object in the List; if the countryCode property matches, a Y is placed in the last column. The following code initializes the Velocity engine, creates a VelocityContext, and renders the template:

import org.apache.velocity.Velocity; import org.apache.velocity.app.VelocityContext; // Initialize Velocity with default properties Velocity.init( ); // Create a List to hold our Airport objects List airports = new ArrayList( ); airports.add( new Airport(1, "ATL", "Hartsfield Atlanta", 76876128, "US" ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.