Templating makes it easier to handle dynamic content on web pages. One of the better templating frameworks for Python is Cheetah. Keep reading to find out more.
Cheetah also contains #return and #pass directives for use in functions that behave just like their Python equivalents.
It's possible to import Python modules in a template using the #import directive:
#import time $time.strftime('%m/%d/%Y')
A #from directive also exists that is identical to Python's from.
You can also import other compiled templates, and it's possible to subclass both compiled templates and Python modules as well. Here, we define parent.tmpl:
One: $one Two: $two Three: $three
Compile it, and then we are able to subclass it and define methods for $one, $two and $three:
#from parent import parent #extends parent #def one 1 #end def #def two 2 #end def #def three 3 #end def
Of course, just because you can play around with logic in Cheetah templates does not mean that you should. Combining presentation and logic wherever possible defeats the purpose of templating, which is to separate the two elements of dynamic content. Too many directives within a template make the template difficult to read, anyway. In my experience, a good rule of thumb is to use template logic where actual layout elements will vary as a result. Otherwise, if it's just a simple message or something that will vary, Python does the job a lot better. More complex layout elements are probably best left to Python, too.
Conclusion
Cheetah offers templating that can be used with just about any Python framework. I should also note that it doesn't have to be used with web pages. It can also be used for XML documents, e-mails and just about any other format. Beyond basic templating, it also allows for logic to be placed within templates, such as conditional statements, loops and functions. It's an easy-to-use tool that's worth taking into consideration for projects that require dynamic content.