ustache¶
Mustache for Python.
Documentation: ustache.readthedocs.io
Installation¶
pip install ustache
Usage¶
Python:
import ustache
print(ustache.render('Hello {{v}}', {'v': 'World!'}))
# Hello World!
Command line:
$ ustache -j data.json -o output.html template.mustache
Highlights¶
The fastest pure-python Mustache implementation to this date.
Command line interface.
Spec compliant, but also highly compatible with
Mustache.js
.Small codebase, efficiently rendering to
str
orbytes
, supporting streaming.Fully customizable behavior: property getter, partial resolver, stringification, escaping and lambdas.
No dynamic code generation, jit and transpiler friendly.
Considerations¶
For inter-compatibility with JavaScript (especially Mustache.js
, enabling
client-side rendering with the same templates), ustache exposes some
atypical behavior:
Mustache blocks stick to JavaScript truthyness (
Mustache.js
truthyness emulation):Empty mappings (such as
dict
) are inconditionally truthy.NaN
/-NaN
are falsy.
Mustache blocks loop through any iterable other than mappings and strings (
Mustache.js
Array
handling).Non-mapping sized objects will expose a virtual
length
property (JavaScriptArray.length
emulation, customizable viagetter
parameter).Mapping keys containing dot (
.
) or whitespace (Mustache.js
property limitation, customizable viagetter
parameter).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
Object
emulation, customizable viagetter
parameter).
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:
$ ustache -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>