Velocity #parse but assign it to a variable

Alex picture Alex · Oct 18, 2008 · Viewed 12.9k times · Source

Say you have a standard template with included (parsed) header, body, footer templates.

In the body template a variable like $subject is defined and you want that also displayed in the header template.

In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)

In velocity it would look something like

set ($body=#parse("body.vm"))

parse("header.vm")

${body}

parse("footer.vm")

This however doesn't seem to work, any thoughts on how to do this?

Answer

Will Glass picture Will Glass · Oct 31, 2008

Either of the two solutions above would work. The VelocityLayoutServlet solution requires an extra package (also from Velocity) called Velocity Tools. I'm partial to this approach (and variants) myself.

A third method is simply to put the #parse within quotes:

set ($body="#parse('body.vm')")

Within a #set, anything in double quotes is evaluated. Strings within single quotes are passed in literally.