9.8. Using Macros in a Templating Engine

Problem

You need to reuse portions of a template to standardize the display of common elements such as an address or a name.

Solution

Use Velocity Macro definitions to reuse logic to print out both names and addresses. Velocity macros are like subroutines that take a set of parameters and perform common tasks. In the following Velocity template, two macros, #name and #address, handle the printing of names and addresses:

#set( $volunteer = $appointment.volunteer ) #set( $location = $appointment.location ) #set( $org = $appointment.organization ) ## Define the "name" macro #macro( name $object )$!object.firstName $!object.lastName#end ## Define the "address" macro #macro( address $object ) $!object.address.street1 $!object.address.street2 $!object.address.city, $!object.address.state $!object.address.zipcode #end #name( $volunteer ), Thank you for volunteering to help serve food at the $location.name next week. This email is a reminder that you are scheduled to help out from $appointment.startTime to $appointment.endTime on $appointment.date. The address of the shelter is: #address( $location ) If you need directions to the shelter click the following URL: ${org.baseUrl}directions?location=${location.id} Also, if you are unable to help out on $appointment.date, please let us know by sending an email to ${org.email} or by filling out the form at this URL: ${org.baseUrl}planschange?appointment=${appointment.id} Thanks again, #name( $org.president ...

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.