根据文件扩展名选择Mako预处理器?
我想要对一个叫做 mako.lookup.TemplateLookup
的东西进行一些设置,让它只对特定文件后缀的文件使用某些预处理器。
具体来说,我有一个叫 haml.preprocessor
的预处理器,我希望它能应用到所有文件名以 .haml
结尾的模板上。
谢谢!
1 个回答
4
你可以自定义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>