Pystache
Pystache is a Python implementation of the Mustache templating language, emphasizing a logic-free approach to separate presentation from application logic. It fully supports the Mustache spec and is currently maintained as a community fork. The latest stable release is 0.6.8, released on March 18, 2025.
Warnings
- breaking Pystache 0.5.0 introduced significant API changes, including the removal of the `View` class and replacement of the `Template` class with `Renderer`. Code written for pre-0.5.0 versions will require updates.
- gotcha The default HTML escape function behaves differently between Python 2 (not escaping single quotes with `cgi.escape()`) and Python 3 (escaping single quotes with `html.escape()`). This can lead to subtle rendering differences or unexpected security issues if not accounted for.
- gotcha Pystache internally uses unicode. When passing byte strings as input (e.g., from files or network), explicit encoding attributes (`file_encoding`, `string_encoding`, `decode_errors`) on the `Renderer` might be necessary to control conversion and prevent `UnicodeDecodeError` or incorrect rendering.
- gotcha If installing from source, Pystache's original code was written for Python 2 and must be converted (e.g., by `2to3`) for Python 3 environments. Importing directly from an unconverted Python 2 source directory in a Python 3 environment will result in a `SyntaxError`.
- gotcha The `{{.}}` tag (implicit iterator) is supported for accessing the current value within a section context (e.g., when iterating over a list of simple values). While useful, its behavior is not always intuitive and was a later addition to the Mustache spec.
Install
-
pip install pystache
Imports
- render
import pystache pystache.render(template, context)
- Renderer
from pystache import Renderer renderer = Renderer()
- TemplateSpec
from pystache.template_spec import TemplateSpec
- View
Quickstart
import pystache
# Simplest rendering
template = "Hello, {{person}}!"
context = {"person": "World"}
print(pystache.render(template, context))
# Using Renderer for more control (e.g., custom template directories)
renderer = pystache.Renderer()
print(renderer.render(template, context))
# Using a dedicated view class (no inheritance needed since 0.5.0)
class SayHello:
def to(self):
return "Pizza"
hello_view = SayHello()
template_view = "Hello, {{to}}!"
print(renderer.render(template_view, hello_view))