Template reuse
Overview
Many part of html files could be duplicates and repeated over and over in all html files; As a principle, code duplication is something we want to avoid.
We can identify such parts and factor them out into separate velocity file(s). Any files that needs those parts can then import them with #parse
directive. The #parse
script element allows the template designer to import a local file that contains VTL. Velocity will parse the VTL and render the template specified.
Template inclusion
Apache Velocity, as well as most other templating languages, offer a way to reuse templates.
info
Template reuse may come under the name of template reuse, or template inheritance, or template inclusion. It means the ability to embed part of a template into another one.
Let's look at authors.vm
:
This is a very small file, but still there are parts that are going to be repeated in any other template files we will add later. Alright, let's create
a new file src/main/resources/public/templates/top.vm
with the following content:
Next, create src/main/resources/public/templates/bottom.vm
:
Finally, update src/main/resources/public/templates/authors.vm
as follows:
As you can see, we import top.vm
and bottom.vm
into authors.vm
. Also, pay attention how we use/refer a varibale that is defined in authors.vm
in top.vm
Rerun the Server.main
again and make sure our refactoring has not introduced any error; everything must work as before!