【发布时间】:2012-01-08 04:50:43
【问题描述】:
我想以某种方式对mako.lookup.TemplateLookup 进行检测,使其仅对某些文件扩展名应用某些预处理器。
具体来说,我有一个haml.preprocessor,我想将其应用于文件名以.haml 结尾的所有模板。
谢谢!
【问题讨论】:
标签: python preprocessor haml mako
我想以某种方式对mako.lookup.TemplateLookup 进行检测,使其仅对某些文件扩展名应用某些预处理器。
具体来说,我有一个haml.preprocessor,我想将其应用于文件名以.haml 结尾的所有模板。
谢谢!
【问题讨论】:
标签: python preprocessor haml mako
您应该能够自定义 TemplateLookup 以获得您想要的行为。
customlookup.py
from mako.lookup import TemplateLookup
import haml
class Lookup(TemplateLookup):
def get_template(self, uri):
if uri.rsplit('.')[1] == 'haml':
# change preprocessor used for this template
default = self.template_args['preprocessor']
self.template_args['preprocessor'] = haml.preprocessor
template = super(Lookup, self).get_template(uri)
# change it back
self.template_args['preprocessor'] = default
else:
template = super(Lookup, self).get_template(uri)
return template
lookup = Lookup(['.'])
print lookup.get_template('index.haml').render()
index.haml
<%inherit file="base.html"/>
<%block name="content">
%h1 Hello
</%block>
base.html
<html>
<body>
<%block name="content"/>
</body>
</html>
【讨论】:
.haml 扩展名时使用,您应该能够混合使用haml/html 模板。
get_template("something.haml") 然后从不是 HAML 的东西继承,它将失败。
self.template_args['preprocessor'] 周围添加一个 RLock 以避免我所在的线程环境中的竞争条件。干杯!