EmPy Templating System
EmPy is a powerful, robust, and mature templating system for Python that allows embedding Python code directly into template text. It processes source documents containing special markup (default: '@') to produce output. The library is currently at version 4.2.1 and has an active development status, with recent updates modernizing its features and Python compatibility.
Warnings
- breaking Major breaking changes occurred in the 4.x series compared to 3.x. This includes relicensing from GPL to BSD, significant changes to markup syntax (e.g., `repr` markup changed to backquote, in-place markup syntax changed), and modifications to the embedding interface. The `Interpreter` constructor and the global `expand` function now strictly require keyword arguments.
- breaking Internal module names and constants were changed in 4.x. For example, the `OVERRIDE_OPT` constant, previously accessible, was removed or refactored, leading to `ImportError` for applications that relied on such internals (e.g., `colcon-core` issues).
- gotcha Multi-line Python statements within `@{...}` blocks must be flush with the left margin of the template. Python's significant indentation rules apply directly to these blocks, and incorrect indentation will lead to `IndentationError` or other parsing failures.
- gotcha There are two distinct Python libraries with very similar names: `empy` (the templating system) and `EMpy` (Electromagnetic Python). They serve entirely different purposes and have different installation commands (`pip install empy` vs `pip install ElectromagneticPython`).
Install
-
pip install empy
Imports
- expand
from em import expand
Quickstart
from em import expand
template_string = '''Hello, @(name)!\nYour lucky number is @(2 * 3 * 7).\n@{for item in items:}\n - @item\n@{}\n'''
context = {
'name': 'World',
'items': ['apple', 'banana', 'cherry']
}
rendered_output = expand(template_string, globals_=context)
print(rendered_output)