Debian Codegraph @

docs/recipes/precompiled.rst

raw
1 Precompiled Templates
2 =====================
3
4 Why bother?
5 -----------
6 Since Cheetah supports two basic modes: dynamic and precompiled templates, you have
7 a lot of options when it comes to utilizing Cheetah, particularly in web environments.
8
9 There is added speed to be gained by using pre-compiled templates, especially when
10 using mod_python with Apache. Precompiling your templates means Apache/mod_python
11 can load your template's generated module into memory and then execution is only
12 limited by the speed of the Python being executed, and not the Cheetah compiler.
13 You can further optimize things by then pre-compiling the generated Python files
14 (.py) down to Python byte-code (.pyc) so save cycles interpreting the Python.
15
16
17 Basic Pre-compilation
18 ---------------------
19 Suppose you have a template that looks something like this::
20
21 #attr title = "This is my Template"
22 <html>
23 <head>
24 <title>\${title}</title>
25 </head>
26 <body>
27 Hello \${who}!
28 </body>
29 </html>
30 **Figure 1. hello.tmpl**
31
32 In order to compile this down to a Python file, you need to only execute the
33 `cheetah compile hello.tmpl` command. The results will be a Python file (.py)
34 which you can then treat as any other Python module in your code base.
35
36
37 Importing and lookup
38 --------------------
39 Typically for the template in *Figure 1*, I could easily import it post-compilation
40 as any other Python module::
41
42 from templates import hello
43
44 def myMethod():
45 tmpl = hello.hello(searchList=[{'who' : 'world'}])
46 results = tmpl.respond()
47
48 **Figure 2. runner.py**
49
50 *Note:* If you use the `\#implements` directive, `respond` may not be your "main
51 method" for executing the Cheetah template. You can adjust the example above in
52 *Figure 2* by using `getattr()` to make the lookup of the main method dynamic::
53
54 def myMethod():
55 tmpl = hello.hello(searchList=[{'who' : 'world'}])
56 mainMethod = getattr(tmpl, '_mainCheetahMethod_for_%s' % tmpl.__class__.__name__)
57 results = getattr(tmpl, mainMethod)()
58
59 **Figure 3. Dynamic runner.py**