Embedding files and/or templates within templates using Velcocity

We can embed a file or other templates within Velocity templates – this is obviously useful for reusing snippets of code/text or whatever in more than file. We still need to create the context mappings for all the template file that form out overall template – in other words we supply the mappings the container template and all of the embedded templates.

To embed a template we simply use the #include or #parse directives. #include is used to pull in a template or file without transforming it using the template engine, i.e. any variables etc. will not be transformed or rendered by Velocity whereas #parse will transform any Velocity variables or code.

Taking the template (template.txt.vm) from my previous post, which looked like this

Hello $name,

This is a $template_name template.

we might break this template into the following two templates

salutation.txt.vm

Hello $name,

and template.txt.vm becomes

#parse("templates/salutation.txt.vm")

This is a $template_name template.

This will result in the combined and transformed template.