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:

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Authors List</title>
</head>
<body>
#if ($authors)
<h1>List of the authors of your favorite books:</h1>
<div class="divContents">
<ol>
<p>
#foreach($author in $authors )
<li class="content author"><i>$author.name</i> ($author.nationality) has published $author.numOfBooks books.</li>
#end
</p>
</ol>
</div>
#end
</body>
</html>

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:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>$title</title>
</head>
<body>

Next, create src/main/resources/public/templates/bottom.vm:

</body>
</html>

Finally, update src/main/resources/public/templates/authors.vm as follows:

#set( $title = "Authors List" )
#parse("public/templates/top.vm")
#if ($authors)
<h1>List of the authors of your favorite books:</h1>
<div class="divContents">
<ol>
<p>
#foreach($author in $authors )
<li class="content author"><i>$author.name</i> ($author.nationality) has published $author.numOfBooks books.</li>
#end
</p>
</ol>
</div>
#end
#parse("public/templates/bottom.vm")

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!