mstache¶
Mustache for Python.
Documentation: mstache.readthedocs.io
License¶
Installation¶
pip install mstache
Usage¶
Python:
import mstache
print(mstache.render('Hello {{v}}', {'v': 'World!'}))
# Hello World!
Command line:
$ mstache -j data.json -o output.html template.mustache
Highlights¶
The fastest pure-python Mustache implementation to this date.
High mustache.js compatibility.
Fully spec compliant up to Mustache v1.4.2, including lambda extension (opt-in).
Support for chevron-style lambdas (opt-out)
Command line interface.
Small codebase, efficiently rendering to
strorbytes, buffered or stream.Fully customizable behavior for caching, property getter, partial resolver, stringification, escaping, chevron lambda render and mustache block line trimming.
Support for binary templates (
bytesandkeep_linesoption).No dynamic code generation, both jit and transpiler friendly.
Considerations¶
For inter-compatibility with JavaScript (especially mustache.js,
to enable client-side rendering the same templates), mstache must behave
somewhat atypically for a Python template engine:
Mustache blocks stick to JavaScript truthyness:
Empty mappings (such as
dict) are unconditionally truthy.NaN/-NaNare falsy.
Mustache blocks do not iterate mappings nor strings.
Sized collections, excluding mappings, will expose a virtual
lengthproperty, customizable viagetterparameter.Mapping keys containing dot (
.) or whitespace () are unreachable (common property limitation), customizable viagetterparameter.Sequence elements are accessible by positive index in the same way mapping integer-keyed items are also accessible when no string key conflicts, as properties (JavaScript
Objectemulation), customizable viagetterparameter.
An special consideration about the Mustache spec: mstache currently passes most mustache spec tests (plus optional lambdas) but one to ensure mustache.js compatibility.
Syntax¶
Check out the mustache(5) manual.
For quick reference, here is a quick overview of the Mustache syntax.
Template (template.mustache):
Data (data.json):
{
"object": {
"property": "Object property value"
},
"null": null,
"array": [
{"property": "Array item1 property"},
{"property": "Array item2 property"},
{"property": "Array item3 property"}
],
"empty_array": [],
"unescaped_html": "<li>this is unescaped html</li>"
}
Command:
$ mstache -j data.json -o output.html template.mustache
Output:
<ul>
<li>Object property value</li>
<li><b>null</b> is falsy</li>
<li>Array item1 property</li>
<li>Array item2 property</li>
<li>Array item3 property</li>
<li>empty_array is empty</li>
<li>this is unescaped html</li>
</ul>