Tempita
Tempita is a very small, simple text templating language designed for text substitution, not as a full-fledged web templating engine. It's suitable for generating Python files, configuration files, or other text-based content when `string.Template` is insufficient, but a heavier solution like Jinja is overkill. The current version is 0.6.0, which is Python 3 only. The project is explicitly in maintenance mode, not actively developed for new features.
Common errors
-
NameError: name 'Template' is not defined
cause The `Template` class was used without being explicitly imported from the `tempita` module.fixAdd `from tempita import Template` at the top of your Python file. -
tempita.TemplateError: Syntax error in template (template_name.html:X:Y)
cause There is a syntax error within the Tempita template string or file, such as a missing `{{endfor}}` or incorrect expression syntax.fixReview the template content around the reported line number (X) and column (Y) in the error message for syntax mistakes. -
TypeError: 'str' does not support the buffer interface (or similar UnicodeDecodeError on Python 2)
cause Attempting to use Tempita 0.6.0+ on a Python 2 environment, or encountering unicode/bytes mixing issues in older versions.fixEnsure your environment is running Python 3 for Tempita 0.6.0+. For older Tempita versions, explicitly encode/decode strings to handle Unicode consistently, usually to UTF-8.
Warnings
- breaking Tempita version 0.6.0 and later removes Python 2 support. Projects upgrading to 0.6.0 must be running on Python 3, or they will encounter compatibility errors.
- gotcha Tempita templates execute arbitrary Python code. This means templates should be treated as trusted code, as untrusted templates could pose a security risk by executing malicious operations.
- gotcha Tempita is not designed for complex web applications or extensive feature sets found in larger templating languages like Jinja. It's intended for simpler text substitution and code generation tasks.
Install
-
pip install tempita
Imports
- Template
import tempita; tempita.Template(...)
from tempita import Template
- sub
from tempita import sub
- HTMLTemplate
from tempita import HTMLTemplate
Quickstart
from tempita import Template, sub
# Using the Template class
tmpl = Template("Hello {{name}}! The answer is {{2 * 3}}.")
output_class = tmpl.substitute(name='World')
print(f"Class Output: {output_class}")
# Using the sub shortcut for immediate substitution
output_shortcut = sub("Welcome, {{user}}!", user='Alice')
print(f"Shortcut Output: {output_shortcut}")
# Example with control flow (if/for) and Python blocks
complex_template = Template("""
<ul>
{{for item in items}}
<li>{{item.upper()}}{{if loop.last}} (last){{endif}}</li>
{{endfor}}
</ul>
{{py: x = 10}}
The value of x is {{x}}.
""")
output_complex = complex_template.substitute(items=['apple', 'banana', 'cherry'])
print("\nComplex Output:")
print(output_complex)