9.6. Using a Simple Templating Language
Problem
You need to produce a parameterized message using a template stored in a file.
Solution
Use Jakarta Velocity and store your template in the filesystem. Jakarta Velocity is a straightforward templating engine with a lightweight syntax similar to the expression language introduced in Recipe 9.2. The following Velocity template is used to create an email:
#set( $customer = $subscription.customer )
#set( $magazine = $subscription.magazine )
$customer.firstName,
Your subscription to ${magazine.title} on
$subscription.endDate. If you are interested in renewing your subscription,
please click on the following URL, and enter your password:
${magazine.baseUrl}/renew?cust=${customer.id}This template references a Subscription bean bound
to the name subscription. This
Subscription object has a
customer property and a
magazine property, and both of these properties
are assigned to a local template variable using the
#set directive. To render a Velocity template, the
engine is initialized using Velocity.init( )
, a VelocityContext is
created and populated, and the template is read with a
FileReader
.
The following code renders this template:
import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; // Initialize Velocity Velocity.init( ); // Create a context and put our subscription object into the context VelocityContext context = new VelocityContext( ); context.put("subscription", testSubscription( )); // Create a Reader ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access