If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Thursday, August 02, 2007

Cheetah Templates

Currently doing some web development and found Cheetah very useful.
I like Cheetah since it's syntax is very similar to Python and I can use my existing Python objects with it.

I have one master template that set the site general site look and feel (with the master CSS of course).
#from time import ctime

#attr NAME = "???"

#def head
#end def

#def body
OOOPS, head will roll...
#end def

<link rel="stylesheet" type="text/css" href="style.css" />
<div class="header">My Wonderful Site - $NAME</div>

<hr />
<div class="footer">
Generated $ctime()
$head and $body are place holders that the specific pages will fill.
Pages also define $NAME which will be shown in the header.

The an specific page (index.tmpl) can be:

#include "master.tmpl"

#attr NAME = "INDEX"

#def body
This is my site index page, see also <a href="other.cgi">other page</a>. <br />

Oh, and also random = $random;
#end def
And the CGI script:


from Cheetah.Template import Template

from random import randint

def main():
random = randint(0, 100)

print "Content-Type: text/html"

page = Template(file="index.tmpl", searchList=[locals()])
print page.respond()

if __name__ == "__main__":
Note that I pass locals() as the search list. This frees me from creating a mapping dictionary (exporting random to the template).

That's about it, you can use the master template and the site main CSS to have a uniform looking site and let each page implement just the $body and $head if it needs to.

No comments:

Blog Archive