…and I do not want to precompile my templates. This one was pretty simple, as there is one recipe on the Cheetah Wiki about it. We start there and just modify it a bit. Here goes. First, we add the following somewhere in our apache config (I added it to my .htaccess):
PythonHandler cheetah
That was easy, now we write the code for cheetah.py:
02: from mod_python import apache
03: from mod_python import Session
04: from Cheetah import Template
05:
06: def handler(req):
07:
08: session = Session.Session(req)
09: req.session = session
10: req.content_type = “text/html”
11: base_path = req.get_options()[’base-path’]
12: template_name = string.replace(req.uri, base_path, “”)
13: template_name = findfile(template_name)
14: template = Template.Template(file=template_name, searchList=[req])
15: content = template.respond()
16: req.send_http_header()
17: req.write(content)
18:
19: return apache.OK
Pretty simple really.
- Set up the imports (1-4)
- define the handler for mod_python to kick in (6)
- (Optional) create a session and add it to the request (8-9)
- tell the client the result will be HTML (10)
- adjust the uri down to a template filename. For instance if the request uri was ‘/example/test.tmpl’, then strip off the ‘/example/’ to come up with ‘test.tmpl’. Note that line 11 could just as easily read
base_path = "/example/"(11,12) - Find the template in the path (this code is found here) (13)
- construct the template, passing in the request object as part of the template’s available namespace. For example, in mod_python, you can get the path of the request uri by
req.uri. In the template, you just use$uri, as thereq.is silent
(14) - ‘fill’ the template (execute it?), returning the string result (15)
- finish the request and return success (16-19)
How much easier can it be? Now you create the template (hello.tmpl):
Hello $place
Now, when you hit http://localhost/example/hello.tmpl, you will see “Hello World”.
Popularity: 14%