19. How to use Cheetah templates with CherryPy

Cheetah is a templating language for python. CherryPy comes with its own templating language (CGTL and CHTL), but if you prefer to use Cheetah, that's very easy to do. More about Cheetah can be found at: http://www.cheetahtemplate.org/.

Here is a sample code that shows how to do it:

#################
# File Root.cpy
#################
from Cheetah.Template import Template
CherryClass Root:
view:
    def index(self):
        template = Template(file='index.tmpl')
        template.colors = ['AA', 'BB', 'CC']
        return template.respond()
    
#################
# File index.tmpl
#################
<html>
<head>
<title>Cheetah Experiment</title>
</head>
#attr $colors = []
#if $colors is []
    #set codelist = ['00','33','66','99','CC','FF']
#else 
    #set codelist = $colors
#end if
<body>
<table border=1>
#for $r in $codelist
    #for $g in $codelist
        <tr>
        #for $b in codelist
        #set color = '#%s%s%s'%(r,g,b)
        <td bgColor = $color>&nbsp;&nbsp; $color &nbsp; </td>
        #end for
    #end for
#end for
</table>
</body>
</html>

Note that this example is not optimized because the template file will be read/parsed/rendered each time the page is displayed. It is quite easy to change that code so it only does it once, or everytime the template file is changed.

Many thanks to "ToddB" for contributing this code :-)

See About this document... for information on suggesting changes.