O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( );
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required