Add Velocity for Dynamic HTML #98
Chapter 12, Miscellany
|
493
HACK
As an example, suppose you want to display the weather for the next three
days as part of your application. You need a nice graphic weather display
showing your users the current weather, as in Figure 12-13.
Velocity and Templates
Velocity is an open source template engine, released under the Apache
Jakarta umbrella. At its simplest, Velocity allows you to add intelligent
replacement from a text file. At its most extreme, Velocity allows you to call
Java methods and use the entire VTL (Velocity Template Language) to cre-
ate intelligent templates using loops, conditionals, and variables. In other
words, you get the power of an MVC infrastructure like JSP, but in a very
lightweight local-client technology.
When using Velocity, you have two basic elements to deal with: the
VelocityContext and the template. The VelocityContext holds objects that
can be referenced from the template. The template is text with imbedded
VTL that controls the Velocity output.
In this simple example,
${name} and ${what} indicate replaceable values:
${name} is a total ${what}
Here is a simple context:
VelocityContext context = new VelocityContext( );
context.put("name", Jonathan);
context.put("what", Rockstar);
Figure 12-13. A graphical weather page

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.