skip to navigation
skip to content

Not Logged In

Cheetah 2.0b4

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

Latest Version: 2.2.1

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

"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
(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.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"

    - 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'
  • $var1-$var2
  • ') $func(c'
  • $var1-$var2
  • ', doSomething=True) $func(content=c'
  • $var1-$var2
  • ', doSomething=True) $func(lambda x,y: c'
  • $x-$y
  • ') $func(callback=lambda x,y: c'
  • $x-$y
  • ') $func(lambda x,y: c'
  • $x-$y-$varInSearchList
  • ') $func(c'
  • $var1-$var2-$(var3*10)-$(94.3*58)
  • ') $func(c'
  • $var1-$var2-$func2(c"a nested expr $var99")
  • ') #if $cond then c'
  • $var1-$var2
  • ' else c'

    $var1-$var2

    ' #def foo(arg1=c'$var1$var2'): blah $arg1 blah $foo(c'$var1$var2') - 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:\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] 1.0 (Dec 4, 2005) !!!THIS RELEASE REQUIRES RECOMPILATION OF ALL COMPILED CHEETAH TEMPLATES!!! Version bump from 1.0rc3