Add Velocity for Dynamic HTML #98
Chapter 12, Miscellany
|
497
HACK
Create a Velocity Context
Now, you need to make a VelocityContext to supply dynamic values to your
template. Create a method called
createContext and loop through the
weather collection, which contains three
Weather
objects:
private VelocityContext createContext(Collection weatherCollection) {
VelocityContext context = new VelocityContext( );
int index = 1;
for (Iterator iterator = weatherCollection.iterator( );
iterator.hasNext( );) {
Weather weather = (Weather) iterator.next( );
//add info to context
index++;
}
return context;
}
Next, create a variable for each day, since all of the VTL is keyed on a mea-
surement, as well as the day (
DAY1, DAY2, or DAY3):
String day = "DAY" + index;
Now, add the day itself, as well as entries for temperature, humidity, and
pressure:
context.put(day, weather.getDay( ));
context.put(day + "_TEMP", weather.getTemperature( ));
context.put(day + "_HUMIDITY", weather.getHumidity( ));
context.put(day + "_PRESSURE", weather.getPressure( ));
Fill the Template with Values
This is the easiest part. The code below is boilerplate code to initialize the
Velocity engine and run a template (
htmlText) through Velocity with a con-
text. It then returns the completed HTML as a
String:
private String processString(VelocityContext context, String htmlText)
throws Exception {
StringWriter writer = new StringWriter( );
Properties properties = new Properties( );
Velocity.init(properties);
Velocity.evaluate(context,
writer,
null,
htmlText);
return writer.getBuffer().toString( );
}

Get Swing Hacks 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.