Cheetah3 Template Engine
Cheetah is a powerful, open-source template engine and code generation tool for Python. It allows developers to generate dynamic web content, source code, and other text-based output from templates using a Python-like syntax. The current stable version is 3.2.6.post1. It maintains a moderate release cadence, focusing on stability and Python 3 compatibility.
Common errors
-
ImportError: No module named 'cheetah'
cause Attempting to import the `cheetah` package with a lowercase namespace, or `cheetah3` is not installed.fixEnsure `cheetah3` is installed (`pip install cheetah3`) and use the capitalized import path: `from Cheetah.Template import Template`. -
NameMapper.NotFound: Can't find 'my_variable' in the searchList
cause A variable used in the template (`$my_variable`) was not found in the data provided to the template instance's search path.fixPass the variable via the `searchList` argument during `Template` initialization (e.g., `Template(template_str, searchList=[{'my_variable': 'value'}])`) or assign it directly to the template instance (`t.my_variable = 'value'`). -
SyntaxError: Non-string object used as a template
cause The first argument to `Template()` must be a string containing the template content. A non-string variable (e.g., a file handle, None) was passed directly.fixEnsure the template content passed to `Template()` is a string. If you want to load from a file, use the `file` keyword argument: `Template(file='my_template.tmpl')`. -
TypeError: 'Class' object is not callable
cause Attempting to instantiate or call a Cheetah directive (like `#def`, `#for`, `#if`) as if it were a Python class or function outside of the template context.fixCheetah directives are part of the template language and are used within the template string itself, not directly in Python code. Ensure directives follow Cheetah's specific template syntax (e.g., `#def myfunc($arg)...#end def`).
Warnings
- breaking The `cheetah3` package requires Python 3.4+. Despite PyPI's `requires_python` metadata potentially suggesting Python 2.7 compatibility, this is incorrect for the `cheetah3` fork. For Python 2.7 support, you must use the older `cheetah` (2.x) package.
- gotcha The top-level import for Cheetah's modules uses a capitalized 'Cheetah' (e.g., `from Cheetah.Template import Template`). Using `cheetah` (lowercase) will result in an `ImportError` because Python's module resolution is case-sensitive.
- gotcha Cheetah templates resolve variables through a 'searchList', which is a list of objects (dictionaries, objects, modules) scanned for attributes. If a variable is not found in any item of the `searchList` or assigned directly, it will raise a `NameMapper.NotFound` error.
- gotcha Cheetah's line comments (`##`) must start at the beginning of a line to be treated as comments. If `##` appears after non-whitespace characters on a line, it will be treated as literal output or cause a template parsing error.
Install
-
pip install cheetah3
Imports
- Template
from cheetah import Template
from Cheetah.Template import Template
- DummyTransaction
from Cheetah.DummyTransaction import DummyTransaction
Quickstart
from Cheetah.Template import Template
import os
# Example template content
template_content = """
#def say_hello($name="Guest")
Hello $name! Welcome to #filter upper $project_name#end filter .
#end def
$say_hello("World")
Today's date is $date.
#if $enable_feature
Feature XYZ is enabled.
#else
Feature XYZ is disabled.
#end if
"""
# Data to pass to the template
project_data = {
'project_name': os.environ.get('CHEETAH_PROJECT_NAME', 'MyCheetahProject'),
'date': '2024-04-16',
'enable_feature': True
}
# Create a Template instance and pass data via searchList
t = Template(template_content, searchList=[project_data])
# Render the template
rendered_output = str(t)
print(rendered_output)
# Example of assigning variables directly
two = Template("The value is $value.")
two.value = 123
print(str(two))