1 "Template support for Cheetah"
5 from Cheetah
import Compiler
8 def _recompile_template(package
, basename
, tfile
, classname
):
9 tmpl
= pkg_resources
.resource_string(package
, "%s.tmpl" % basename
)
10 c
= Compiler
.Compiler(source
=tmpl
, mainClassName
='GenTemplate')
12 mod
= imp
.new_module(classname
)
15 tempclass
= ns
.get("GenTemplate",
16 ns
.get('DynamicallyCompiledCheetahTemplate'))
18 tempclass
.__name
__ = basename
19 setattr(mod
, basename
, tempclass
)
20 sys
.modules
[classname
] = mod
26 def __init__(self
, extra_vars_func
=None, options
=None):
29 self
.get_extra_vars
= extra_vars_func
30 self
.options
= options
31 self
.compiledTemplates
= {}
34 def load_template(self
, template
=None,
35 template_string
=None, template_file
=None,
37 """Searches for a template along the Python path.
39 Template files must end in ".tmpl" and be in legitimate packages.
41 given
= len(filter(None, (template
, template_string
, template_file
)))
44 "You may give only one of template, template_string, and "
48 "You must give one of template, template_string, or "
51 return self
.load_template_module(template
)
53 return self
.load_template_string(template_string
)
55 return self
.load_template_file(template_file
)
57 def load_template_module(self
, classname
):
59 ct
= self
.compiledTemplates
61 divider
= classname
.rfind(".")
63 package
= classname
[0:divider
]
64 basename
= classname
[divider
+1:]
66 raise ValueError, "All templates must be in a package"
68 if not self
.options
.get("cheetah.precompiled", False):
69 tfile
= pkg_resources
.resource_filename(package
,
73 if ct
.has_key(classname
):
74 mtime
= os
.stat(tfile
).st_mtime
75 if ct
[classname
] != mtime
:
77 del sys
.modules
[classname
]
78 mod
= _recompile_template(package
, basename
,
81 mod
= __import__(classname
, dict(), dict(), [basename
])
83 ct
[classname
] = os
.stat(tfile
).st_mtime
84 mod
= _recompile_template(package
, basename
,
87 mod
= __import__(classname
, dict(), dict(), [basename
])
88 tempclass
= getattr(mod
, basename
)
91 def load_template_string(self
, content
):
92 raise NotImplementedError
94 def load_template_file(self
, filename
):
95 raise NotImplementedError
97 def render(self
, info
, format
="html", fragment
=False, template
=None,
98 template_string
=None, template_file
=None):
99 tclass
= self
.load_template(
100 template
=template
, template_string
=template_string
,
101 template_file
=template_file
)
102 if self
.get_extra_vars
:
103 extra
= self
.get_extra_vars()
106 tempobj
= tclass(searchList
=[info
, extra
])
108 return tempobj
.fragment()
110 return tempobj
.respond()