I'm new to Mustache.
Many templating languages (e.g., Django / Jinja) will let you extend a "parent" template like so...
<html><head></head> <body> {% block content %}{% endblock %} </body> </html>
{% extends "base.html" %} {% block content %}<h1>Foobar!</h1>{% endblock %}
<html><head></head> <body> <h1>Foobar!</h1> </body> </html>
I'm aware of Mustache's partials (e.g., {{>content}}
), but those seem to be just includes.
Does template extension exist for Mustache? Or, failing that, is there at least some design pattern that effectively turns includes into template extension equivalents.
Mustache is a logicless template engine for creating dynamic content like HTML, configuration files among other things.
Mustache is a logic-less templating system. It permits you to use pre-written text files with placeholders that will be replaced at run-time with values particular to a given request.
A mustache template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. {{person}} is a tag, as is {{#person}} . In both examples we refer to person as the tag's key.
Mustache is a simple web template system. It is available for many programming languages including JavaScript and Java. Mustache is described as a logic-less template engine because it does not have any explicit control flow statements, such as if and else conditionals or for loops.
I recently found myself in the same boat, except I came from a mako background.
Mustache does not allow for template extension/inheritance but there are a few options available to you that I know of.
You could use partials:
{{>header}} Hello {{name}} {{>footer}}
You could inject template pre-processing functions into the context for each template that needs to inherit from some other page:
{{#extendBase}} Hello {{name}} {{/extendBase}}
Hash:
{ "name": "Walden", "extendBase": function() { return function(text) { return "<html><head></head>" + render(text) + "</body></html>" } } }
Prepend and append the desired HTML to the relevant pages in your controller.
Have a layout template ala:
{{>header}} {{{body}}} {{>footer}}
And render the body in your controller, passing that to the layout template as a variable named body
.
Implement template inheritance, pre-mustache, in your code that loads templates.
I wouldn't, however, use the triple mustache because I don't want unescaped HTML to be appearing anywhere, it's just too risky in my opinion.
If someone else has a better solution to this problem I'd love to hear it as well, since I haven't yet taken the plunge in any one of these directions.
I've proposed this to the specification for Mustache here:
https://github.com/mustache/spec/issues/38
Currently mustache.java, hogan.js and phly_mustache support template inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With