O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

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

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 ...

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