Skip to main content

Cheetah is a Python-powered template engine and code-generator.

Project description

Cheetah is a Python-powered template engine and code-generator.
It is similar to the Jakarta project's Velocity.

For a high-level introduction to Cheetah please refer to the User's Guide

Mailing list
Subscribe at

"I'm enamored with Cheetah" - Sam Ruby

"Give Cheetah a try. You won't regret it." - Alex Martelli

"Cheetah is a truly powerful system" - Alex Martelli

"Cheetah is a serious contender for the 'best of breed' Python templating" -
Alex Martelli

"People with a strong PHP background absolutely love Cheetah for being Smarty,
but much, much better." - Marek Baczynski

"I am using Smarty and I know it very well, but compiled Cheetah Templates with
its inheritance approach is much powerful and easier to use than Smarty." -
Jarosław Zabiełło

"There is no better solution than Cheetah" - Wilk

"A cheetah template can inherit from a python class, or a cheetah template, and
a Python class can inherit from a cheetah template. This brings the full power
of OO programming facilities to the templating system, and simply blows away
other templating systems" - Mike Meyer

"Cheetah has successfully been introduced as a replacement for the overweight
XSL Templates for code generation. Despite the power of XSL (and notably XPath
expressions), code generation is better suited to Cheetah as templates are much
easier to implement and manage." - The FEAR development team

"I've used Cheetah quite a bit and it's a very good package" - Kevin Dangoor

Recent Changes

2.0b3 (Jan 5, 2006)
Core Changes: [TR]
- added #yield statement
- added ability to create nested scopes/functions via nested #def statements
- added new #call directive and related #arg directive, per Ian Bicking's
- added new expression syntax c"text $placeholder text"

for those basic function calling cases where you just need to pass in a
small bit of cheetah output as an argument:

c'a string with $placeholders',
c'''a string with $placeholders''',
c"a string with $placeholders",
c"""a string with $placeholders"""

- They can't contain #directives, but accept any valid $placeholder syntax
except caching placeholders. Caching placeholders don't make any sense in
this context.
- They can be used *any* place where a python expression is expected.
- They can be nested to any depth.

$func(c'<li>$var1-$var2</li>', doSomething=True)
$func(content=c'<li>$var1-$var2</li>', doSomething=True)
$func(lambda x,y: c'<li>$x-$y</li>')
$func(callback=lambda x,y: c'<li>$x-$y</li>')
$func(lambda x,y: c'<li>$x-$y-$varInSearchList</li>')
$func(c'<li>$var1-$var2-$func2(c"a nested expr $var99")</li>')
#if $cond then c'<li>$var1-$var2</li>' else c'<p>$var1-$var2</p>'
#def foo(arg1=c'$var1<span class="foo">$var2</span>'): blah $arg1 blah

- added preprocessor hooks to Template.compile()
can be used for partial completion or 'compile-time-caching'
... more details and examples coming. It's very useful, but takes a bit
of explaining.
- added '#set module varName = expr' for adding module globals. JJ's suggestion
- improved generated docstring notes about cached vars
- fixed silly bug related to """ in docstring comments and statements like
this '#def foo: $str("""foo""")'. Reported by JJ.
- changed the handling of single-line defs so that
'#def xxx:<just whitespace>\n' will be treated as a multi-line #def.
The same applies to #block. There's a compiler setting to turn this off
if you really need empty single-line #def:'s.
JJ reported that this was causing great confusion with beginners.
- improved error message for unclosed directives, per Mike Orr's suggestion.
- added optional support for passing the trans arg to methods via **KWS rather
than trans=None. See the discussion on the mailing list Jan 4th (JJ's
post) for
details. The purpose is to avoid an positional argument clash that
apparently is very confusing for beginners.

Note that any existing client code that passing the trans arg in
positionally rather than as a keyword will break as a result. WebKit
does this with the .respond method so I've kept the old style there.
You can also turn this new behaviour off by either manually including
the trans arg in your method signature (see the example below) or by
using the compiler setting 'useKWsDictArgForPassingTrans'=False.

#def manualOverride(arg1, trans=None)
foo $arg1
#end def

- made the ImportHook more robust against compilation errors during import [TR]

Install scripts: [TR]
- added optional support for pje's setuptools
- added cheeseshop classifiers
- removed out of date install instructions in

Servlet Base Class For Webkit: [TR]
- disabled assignment of self.application (was a webware hack)

Unit Tests: [TR]
- unit tests for most of the new syntax elements
- tidied up some old tests
- misc refactoring

2.0b2 (Dec 30, 2005)

Core Changes:
- In previous versions of Cheetah tracebacks from exceptions that were raised
inside dynamically compiled Cheetah templates were opaque because
Python didn't have access to a python source file to use in the traceback:

File "/usr/local/unsnarl/lib/python/us/ui/views/",
line 192, in getTextiledContent
content = str(template(searchList=searchList))
"", line 202,
in __str__
"", line 187,
in respond
"", line 139,
in writeBody
ZeroDivisionError: integer division or modulo by zero

It is now possible to keep the generated source code from the python
classes returned by Template.compile() in a cache dir. Having these files
around allows Python to include the actual source lines in tracebacks and
makes them much easier to understand:

File "/usr/local/unsnarl/lib/python/us/ui/views/",
line 192, in getTextiledContent
content = str(template(searchList=searchList))
File "/tmp/tmp9OVLwe/", line 202, in __str__
def __str__(self): return self.respond()
File "/tmp/tmp9OVLwe/", line 187, in respond
File "/tmp/tmp9OVLwe/", line 139, in writeBody
__v = 0/0 # $(0/0)
ZeroDivisionError: integer division or modulo by zero

This is turned off by default. To turn it on, do this:

class NiceTracebackTemplate(Template):
_keepGeneratedPythonModulesForTracebacks = True
_cacheDirForGeneratedPythonModules = 'xxxx' # change to a dirname

templateClass = NiceTracebackTemplate.compile(src)

This only works with the new Template.compile(src) usage style!

Note, Cheetah generated modules that are compiled on the command line have
never been affected by this issue. [TR]

- added an extra comment per $placeholder to generated python code so it is
easier to grok. [TR]

2.0b1 (Dec 29, 2005)

Core Changes:
- enabled use of any expression in ${placeholders}. See the examples I posted to
the email list on Dec 12th. All use cases of the #echo directive can now
be handled with ${placeholders}. This came from a suggestion by Mike
Orr. [TR]

- made it possible for templates to #extend (aka subclass) any arbitrary
baseclass, including Python's new style classes. You must either compile
your classes on the command line or use the new classmethod
Template.compile() as described below. The old Template(src) interface
still works, provided you don't try to use this new arbitrary baseclass
stuff. See my messages to the email list for more details. [TR]

- made it possible to create template classes dynamically, rather than just
instances. See the new classmethod Template.compile(). See my messages
to the email list for more details. [TR]

klass = Template.compile(src)

- made it easier to work with custom compiler settings, particularly from
the command line tool. You can now define a subclass of Template which
will compile your templates using custom compilerSettings, or even a
custom compiler class, without requiring you to manually pass in your
compilerSettings each time or define them in the template src itself via
the #compiler directive. You can make the command line tool use your
subclass by defining the environment variable CHEETAH_TEMPLATE_CLASS. It
should be in the form 'package.module:class'. See my messages
to the email list for more details. [TR]

- made it possible to pass the searchList in as an argument to #def'ined
methods. This makes all lookup that occur within the scope of that method
use the provided searchList rather than self._searchList. This does not
carry over to other methods called within the top method, unless they
explicitly accept the searchList in their signature AND you pass it to
them when calling them. This behaviour can be turned off with the
corresponding compilerSetting 'allowSearchListAsMethArg' [TR]

- added hooks for filtering / restricting dangerous stuff in cheetah source
code at compile time. These hooks can be used to enable Cheetah template
authoring by untrusted users. See my messages to the email list for more
details. Note, it filters expressions at parse/compile time, unlike Python's
old rexec module which restricted the Python environment at runtime. [TR]

# Here are the relevant compiler settings:
# use lower case keys here!!
'disabledDirectives':[], # list of directive keys, without the start token
'enabledDirectives':[], # list of directive keys, without the start token

'disabledDirectiveHooks':[], # callable(parser, directiveKey),
# called when a disabled directive is found, prior to raising an

'preparseDirectiveHooks':[], # callable(parser, directiveKey)
'postparseDirectiveHooks':[], # callable(parser, directiveKey)

'preparsePlaceholderHooks':[], # callable(parser)
'postparsePlaceholderHooks':[], # callable(parser)

# callable(parser, expr, exprType, rawExpr=None, startPos=None)
# exprType is the name of the directive, 'psp', or 'placeholder'.
#all lowercase

- added support for a short EOLSlurpToken to supplement the #slurp
directive. It's currently re.compile('#\s*\n') (i.e # followed by
arbitrary whitespace and a new line), but this is not set in stone. One
other suggestion was the backslash char, but I believe Python's own
interpretation of backslashes will lead to confusion. The compiler
setting 'EOLSlurpToken' controls this. You can turn it off completely by
setting 'EOLSlurpToken' to None. See the email list for more details. [TR]

- added '_CHEETAH_' prefix to all instance attribute names in compiled
templates. This is related to the arbitrary baseclass change. [TR]

- shifted instance attribute setup to _initCheetahAttributes() method. This
is related to the arbitrary baseclass change. [TR]

- made it possible to use full expressions in the #extends directive, rather
than just dotted names. This allows you to do things like this:

#from xx.TemplateRepository import getTemplateClass
#extends getTemplateClass('someName')

I don't expect this to be used much. I needed it for a wiki system in
which the baseclasses for the templates are dynamically compiled at run
time and are not available via simple imports. [TR]

- added compiler setting autoImportForExtendDirective=True, so this existing
default behaviour can be turned off when needed. [TR]

- fixed a bug in the parsing of single-line #def's and #block's when they
are enclosed within #if ... #end if. Reported by Marcin Gajda [TR]

- tweak to remove needless write('') calls in generated code [TR]

The command line tool (
- added code to cleanup trailing slashes on path arguments (code originally
from Mike Orr) [TR]
- turned on the ImportHooks by default for the 'cheetah fill' command. See the
discussion on the email list [TR]

- fixed a name error bug in the ImportHooks [TR]

1.0 (Dec 4, 2005)

Version bump from 1.0rc3

1.0rc3 (Nov 30, 2005)

- added useSearchList compiler setting [TR]
This defaults to True, but if false, the compiler assumes the first
portion of a $variable (before the first dot) is a global, builtin, or local
var that doesn't need looking up in the searchlist. NameMapper's unified
dotted notation will still be used on the rest of the lookup (provide the
setting useNameMapper==True):

1.0rc2 (Nov 19, 2005)


See my email to the cheetahtemplate-discuss list on Sat. Nov. 12th for more
details on these changes:

- faster list-based buffering in DummyTrans, rather than StringIO (my
benchmarks showed it to be significantly faster. collections.deque wasn't
any faster than a simple list.) [TR]
- new CompilerSettings to tweak generated code: [TR]
* alwaysFilterNone: filter out None immediately, before the filter is called
* useFilters: allows you to turn them off completely and default to str()
* includeRawExprInFilterArgs: allows you to disable this behaviour
* autoAssignDummyTransactionToSelf: off by default
- and automatic $trans finding without having to pass it as an arg to methods
based Jonathan Mark's suggestion. If the template's self.transaction
attribute has been set, each method of the template will use it when
called. [TR]
- applied Chris Murphy's patch to fix a bug in the #shBang directive. [TR]

1.0rc1 (Nov 2, 2005)


- added the compiler option "useStackFrames" for optionally turning off the
default lookup method which doesn't work with psyco because it uses stack
frame introspection. When useStackFrames=False, an alternative psyco
friendly lookup method is used. [TR]

- fixed treatment of None in several filters, bug reported by Daniele Varrazzo

Project details

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page