Cheetah3 Template Engine

3.2.6.post1 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple Cheetah template, pass variables using a search list, define and call a macro (`#def`), use filters (`#filter`), and render the output. It also shows direct variable assignment.

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))

view raw JSON →