Mustache Inheritance

Ju
2 min readMay 16, 2021

Mustache Template has been a very “stable” templating language for years. There have been only a few corner cases are updated in the Mustache specification. However, in recent days, Mustache Specification has a pretty new feature getting updated called “Inheritance”.

To get you some idea of what it is, let’s look at an example.

Considering we have two template files: “base.mustache”, “index.mustache”.

  • base.mustache:
<!doctype>
<html>
<head><title>{{$ title }}My WebSite{{/ title }}</title></head>
<body>{{$ body }}Loading...{{/ body }}</body>
</html>
  • index.mustache
{{< base }}
{{$ title }}Index{{/ title }}
{{$ body }}You are viewing index page.{{/ body }}
{{/ base }}

When rendering the index.mustache, you’ll get something like below:

<html>
<head><title>Index</title></head>
<body>You are viewing index page.</body>
</html>

You may omit all {{$ .. }} block in index.mustache file, if that’s the case, all of the block tags are using the default content.

Check out the specification YAML file to find out more of its characteristics:

As of now, not many of the Mustache implementations have updated themselves so this feature may not be available. For whoever is using Nim-Mustache, you’ll be pleased though because I have released a new version (v0.4.1). :)

Conclusion

Mustache Inheritance makes it available to override tags in a pre-defined base template file.

--

--