Include header and footer in a Mustache template

Filed under: Java, Web, — Tags: Include template, Mustache, Template — Thomas Sundberg — 2015-06-19

A template for creating web pages is great if you want to integrate front- and backend easy. I have been using Mustache for a while and I'm quite satisfied. It works great with both Dropwizard and Spark

The documentation says how to include a snippet from another template. But searching for it was not that easy.

The problem I would like to solve is to reuse the same header and footer on many web pages. That is, include a snippet from another template into a template.

The solution is to refer to a another template from a template using {{> other_template }} in it.

Given this template:

index.mustache

{{> header}}

<p>Page content</p>

{{> footer}}

This header:

header.mustache

<!DOCTYPE HTML>
<html>
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
          rel="stylesheet">
</head>

<body>

And this footer:

footer.mustache

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</body>

</html>

The header.mustache and footer.mustache will be included in index.mustache The result is a web page like this:

result.html

<!DOCTYPE HTML>
<html>
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
          rel="stylesheet">
</head>

<body>
<p>Page content</p>

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</body>

</html>

This solves my problem with the same header and footer on each page using Mustache. Using the template system is different if you use Dropwizard, Spark or any other tool. But that is out of scope today.

Acknowledgements

I would like to thank Malin Ekholm and Johan Helmfrid for proof reading.

Resources



(less...)

Pages

About
Events
Why

Categories

Agile
Automation
BDD
Clean code
Continuous delivery
Continuous deployment
Continuous integration
Cucumber
Culture
Design
Executable specification
Gradle
Guice
J2EE
JUnit
Java
Linux
Load testing
Maven
Mockito
Pair programming
PicoContainer
Programming
Public speaking
Quality
Recruiting
Requirements
Scala
Selenium
Software craftsmanship
Software development
Spring
TDD
Teaching
Technical debt
Test automation
Tools
Web
Windows
eXtreme Programming

Authors

Thomas Sundberg
Adrian Bolboaca

Archives

Meta

rss RSS