A fast, PEP8-compliant Python implementation of the Mustache templating language
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
A fast, PEP8-compliant Python implementation of the Mustache templating language. Chevron provides logic-less template rendering with full spec compliance, running significantly faster than alternative implementations while supporting advanced features like partials, lambda functions, and variable scoping.
pip install chevronimport chevronFor command-line usage:
chevron template.mustache -d data.jsonimport chevron
# Basic string templating
result = chevron.render('Hello, {{ name }}!', {'name': 'World'})
print(result) # "Hello, World!"
# File-based templating
with open('template.mustache', 'r') as template_file:
result = chevron.render(template_file, {'name': 'World'})
# Using partials (template includes)
result = chevron.render(
'Hello, {{> greeting }}!',
{'name': 'World'},
partials_dict={'greeting': '{{ name }}'}
)
# File-based template with JSON data
result = chevron.main('template.mustache', 'data.json')
# File-based template with YAML data (requires PyYAML)
result = chevron.main('template.mustache', 'data.yaml', yaml_loader='SafeLoader')Chevron uses a two-stage rendering process:
This separation enables efficient template caching, custom delimiter support, and robust error handling while maintaining full Mustache specification compliance.
The core template rendering functionality that processes Mustache templates with data context, supporting all Mustache specification features including variables, sections, inverted sections, comments, partials, and custom delimiters.
def render(template='', data={}, partials_path='.', partials_ext='mustache',
partials_dict={}, padding='', def_ldel='{{', def_rdel='}}',
scopes=None, warn=False, keep=False):
"""
Render a mustache template.
Parameters:
- template: str or file-like object, the mustache template
- data: dict, python dictionary with your data scope (default: {})
- partials_path: str, path to directory containing partials (default: '.')
- partials_ext: str, extension for partial files (default: 'mustache')
- partials_dict: dict, dictionary of partials (default: {})
- padding: str, internal padding parameter (default: '')
- def_ldel: str, default left delimiter (default: '{{')
- def_rdel: str, default right delimiter (default: '}}')
- scopes: list, list of scopes for key lookup (default: None)
- warn: bool, issue warnings for missing keys to stderr (default: False)
- keep: bool, keep unreplaced tags when keys not found (default: False)
Returns:
str: Rendered template as string
"""High-level convenience function for rendering templates from files with optional JSON/YAML data files, providing automatic file handling and data loading.
def main(template, data=None, yaml_loader='SafeLoader', **kwargs):
"""
Render mustache template from file paths.
Parameters:
- template: str, path to mustache template file
- data: str or None, path to JSON/YAML data file (optional)
- yaml_loader: str, YAML loader class name when PyYAML is available (default: 'SafeLoader')
- **kwargs: additional arguments passed to render()
Returns:
str: Rendered template as string
"""Entry point for command-line template rendering with argument parsing and error handling, supporting all rendering options through command-line flags.
def cli_main():
"""
Command-line interface entry point.
Processes command-line arguments and renders templates to stdout.
Supports template files, data files, partials configuration,
custom delimiters, and warning options.
Parameters:
None (uses sys.argv for command-line arguments)
Returns:
None (outputs to stdout, exits on error)
"""class ChevronError(SyntaxError):
"""
Custom exception for Chevron-specific template syntax errors.
Raised when template parsing encounters syntax errors such as:
- Unclosed tags
- Mismatched section start/end tags
- Invalid delimiter syntax
- Unexpected end of file
"""import chevron
# Dictionary-based partials
template = 'Hello, {{> greeting }}!'
data = {'name': 'World'}
partials = {'greeting': '{{ name }}'}
result = chevron.render(template, data, partials_dict=partials)
# Output: "Hello, World!"
# File-based partials
# Assuming ./partials/header.mustache contains "Welcome, {{ name }}!"
template = '{{> header }} How are you?'
result = chevron.render(
template,
{'name': 'Alice'},
partials_path='./partials',
partials_ext='mustache'
)
# Output: "Welcome, Alice! How are you?"import chevron
def upper_case(text, render):
"""Convert rendered text to uppercase"""
return render(text).upper()
def bold(text, render):
"""Wrap rendered text in HTML bold tags"""
return '<b>' + render(text) + '</b>'
template = '{{# upper }} Hello {{ name }} {{/ upper }} and {{# bold }} {{ greeting }} {{/ bold }}'
data = {
'name': 'world',
'greeting': 'welcome',
'upper': upper_case,
'bold': bold
}
result = chevron.render(template, data)
# Output: "HELLO WORLD and <b>welcome</b>"import chevron
# Use different delimiters to avoid conflicts
template = 'Hello, <% name %>! Cost: ${{ price }} (<%{ unescaped }%>)'
data = {'name': 'Alice', 'price': '10.00', 'unescaped': '<script>'}
result = chevron.render(template, data, def_ldel='<%', def_rdel='%>')
# Output: "Hello, Alice! Cost: $10.00 (<script>)"import chevron
try:
result = chevron.render('{{# section }} unclosed section', {})
except chevron.ChevronError as e:
print(f"Template error: {e}")
# Output: "Template error: Unexpected EOF..."
# Warning mode for missing keys
template = 'Hello {{ name }} and {{ missing_key }}!'
result = chevron.render(template, {'name': 'World'}, warn=True)
# Prints warning to stderr: "Could not find key 'missing_key'"
# Output: "Hello World and !"
# Keep mode preserves unreplaced tags
result = chevron.render(template, {'name': 'World'}, keep=True)
# Output: "Hello World and {{ missing_key }}!"Install with Tessl CLI
npx tessl i tessl/pypi-chevron