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.

Documentation
================================================================================
For a high-level introduction to Cheetah please refer to the User's Guide
at http://cheetahtemplate.org/learn.html

Mailing list
================================================================================
cheetahtemplate-discuss@lists.sourceforge.net
Subscribe at http://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss

Praise
================================================================================
"I'm enamored with Cheetah" - Sam Ruby, senior member of IBM Emerging
Technologies Group & director of Apache Software Foundation

“Give Cheetah a try. You won't regret it. ... Cheetah is a truly powerful
system. ... Cheetah is a serious contender for the 'best of breed' Python
templating.”-Alex Martelli, Google uber techie, core Python developer & author
of several popular Python books


"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
(http://fear.sourceforge.net/docs/latest/guide/Build.html#id2550573)

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

Recent Changes
================================================================================
2.0rc1 (Jan 10, 2006)
!!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!!
Core Changes: [TR]
- made it possible nest #filter directives
- added lots more docstring content in the Template class
- added Template.subclass() classmethod for quickly creating subclasses of
existing Cheetah template classes. It takes the same args as the
.compile() classmethod and returns a template that is a subclass of the
template .subclass() is called from:
T1 = Template.compile(' foo - $meth1 - bar\n#def meth1: this is T1.meth1')
T2 = T1.subclass('#implements meth1\n this is T2.meth1')

- added baseclass arg to Template.compile(). It simplifies the reuse of
dynamically compiled templates:
# example 1, quickly subclassing a normal Python class and using its
# __init__ call signature:
dictTemplate = Template.compile('hello $name from $caller', baseclass=dict)
print dictTemplate(name='world', caller='me')

# example 2, mixing a Cheetah method into a class definition:
class Foo(dict):
def meth1(self):
return 'foo'
def meth2(self):
return 'bar'
Foo = Template.compile('#implements meth3\nhello $name from $caller',
baseclass=Foo)
print Foo(name='world', caller='me')

A side-benefit is the possibility to use the same Cheetah source with
several baseclass, as the baseclass is orthogonal to the source code,
unlike the #extends directive.

- added 'namespaces' as an alias for 'searchList' in Template.__init__
- made it possible to pass in a single namespace to 'searchList', which will
automatically be converted into a list.
- fixed issue with buffering and use of #call when template is used as a
webkit servlet
- added Cheetah.Utils.htmlEncode and htmlDecode

The command line tool (CheetahWrapper.py):
- changed insertion order for the --env and --pickle options so they match the
commandline UI of the compiled template modules themselves [TR]

2.0b5 (Jan 7, 2006)
!!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!!
Core Changes: [TR]
- made Cheetah.Template a new-style class by inserting 'object' into its'
inheritance tree. Templates can now use super(), properties and all the
other goodies that come with new-style classes.
- removed the WebInputMixin by placing its one method directly in the
Template class.
- removed the SettingsManager Mixin. It wasn't being used by anything
anymore.
- added a framework for caching the results of compilations in
Template.compile(). This is on by default and protects against bad
performance issues that are due to programmers misguidedly compiling
templates inside tight loops. It also saves on memory usage.
- misc attr name changes to avoid namespace pollution
- more + improved docstrings
- replaced the oldstyle dynamic compile hacks with a wrapper around
Template.compile(). The old usage pattern Template(src) now benefits from
most of the recent changes.
Template(src).__class__ == Template.compile(src)
- removed all the extra imports required by oldstyle dynamic compile hacks
- converted the cheetah #include mechanism to newstyle compilation and made it
more flexible
- made the #include mechanism work with file objects in addition to file names
- made the handling of args to Template.compile() more flexible. You can now
provide defaults via class attributes.
- made preprocessors for Template.compile() work with file arguments
- added support for specifying a __metaclass__ on cheetah template classes
- refactored both the class and instance initialization processes
- improved the handling of __str__ in _assignRequiredMethodsToClass

The command line tool (CheetahWrapper.py): [TR]
- improved error output in CheetahWrapper
- switched fill command over to new style compile usage

Unit tests: [TR]
- fixed format string bug in unittest_local_copy.py

2.0b4 (Jan 6, 2006)
!!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!!
Core Changes: [TR]
- fixed up parsing of target lists in for loops. This was previously limited
to fairly simple target lists.
#for ($i, $j) in [('aa','bb'),('cc','dd')]
$i.upper,$j.upper
#end for"
#for (i, j) in [('aa','bb'),('cc','dd')]
$i.upper,$j.upper
#end for"
#for i,(j, k) in enumerate([('aa','bb'),('cc','dd')])
$j.upper,$k.upper
#end for"
- refactored the class initialization process
- improved handling of target lists in #set directive. This was previously
limited to fairly simple target lists.
#set i,j = [1,2] ... #set $i,$j = [1,2]
#set (i,j) = [1,2] ... #set ($i,$j) = [1,2]
#set i, (j,k) = [1,(2,3)] ... #set $i, ($j,$k) = [1,(2,3)]

- made it possible for the expressionFilter hooks to modify the code chunks
they are fed. Also documented the hooks in a docstring. Thus the hooks
can be used as preprocessors for expressions, 'restricted execution', or
even enforcement of style guidelines.

- removed cheetah junk from docstrings and placed it all in comments or
__moduleVars__. Per JJ's suggestion.

- made it possible to nest #cache directives to any level
- made it possible to nest #call directives to any level

Unit Tests [TR]
- extended tests for #for directive
- expanded tests for #set directive
- expanded tests for #call directive
- expanded tests for #cache directive
- added basic tests for the new $placeholder string expressions:
c'text $placeholder text'

2.0b3 (Jan 5, 2006)
!!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!!
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
suggestion.
- 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>')
$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-$(var3*10)-$(94.3*58)</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
$foo(c'$var1<i>$var2</i>')

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

ImportHooks:
- 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 __init__.py

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)
!!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!!

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/WikiPageRenderer.py",
line 192, in getTextiledContent
content = str(template(searchList=searchList))
File
"cheetah_DynamicallyCompiledCheetahTemplate_2005123013020776922.py", line 202,
in __str__
File
"cheetah_DynamicallyCompiledCheetahTemplate_2005123013020776922.py", line 187,
in respond
File
"cheetah_DynamicallyCompiledCheetahTemplate_2005123013020788104.py", 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/WikiPageRenderer.py",
line 192, in getTextiledContent
content = str(template(searchList=searchList))
File "/tmp/tmp9OVLwe/cheetah_2005123012172480269.py", line 202, in __str__
def __str__(self): return self.respond()
File "/tmp/tmp9OVLwe/cheetah_2005123012172480269.py", line 187, in respond
self.writeBody(trans=trans)
File "/tmp/tmp9OVLwe/cheetah_2005123012172449990.py", 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)
!!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!!

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
exception

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

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

'expressionFilterHooks':[],
# 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 (CheetahWrapper.py):
- 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]

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

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