If you use Cheetah, please support the project and register by clicking here:


4.6 Object-Oriented Documents

Because Cheetah documents are actually class definitions, templates may inherit from one another in a natural way, using regular Python semantics. For instance, consider this template, FrogBase.tmpl:

#def title
This document has not defined its title
#end def
#def htTitle
$title
#end def
<HTML><HEAD>
<TITLE>$title</TITLE>
</HEAD><BODY>
<H1>$htTitle</H1>
$body
</BODY></HTML>

And its subclassed document, Frog1.tmpl:

#from FrogBase import FrogBase
#extends FrogBase
#def title
The Frog Page
#end def
#def htTitle
The <IMG SRC="Frog.png"> page
#end def
#def body
... lots of info about frogs ...
#end def

This is a classic use of inheritance. The parent ``template'' is simply an abstract superclass. Each document specializes the output of its parent. For instance, here the parent defines $htTitle so that by default it's identical to whatever the $title is, but it can also be customized.

In many other templating systems, you'd have to use case statements or if-elseif blocks of some sort, repeated in many different sections of code.

While we show another Cheetah document inheriting from this parent, a Python class can inherit from it just as easily. This Python class could define its programmatically-driven value for $body and $title, simply by defining body() and title() methods that return a string. (Actually they can return anything, but we'll get into that later.)

from FrogBase import FrogBase
class Frog2(FrogBase):
	def title(self):
		return "Frog 2 Page"
	# We don't override .htTitle, so it defaults to "Frog 2 Page" too.
	def body(self):
		return " ... more info about frogs ..."

Similarly, the Cheetah document can inherit from an arbitrary class. That's how Cheetah makes templates usable as Webware servlets, by subclassing Servlet. This technique should be possible for non-Webware systems too.

(Note: FrogBase.tmpl could be improved by using the #block directive, section 8.8.)

If you use Cheetah, please support the project and register by clicking here: