看完了mako的文档,寻思着把这的模板改成mako的,顺便熟悉下mako的语法。
在django1.2中官方增加了对第三方模板的支持(见:http://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language),琢磨了一会后开始配置django下的mako。
修改项目下的__init__.py文件,重写掉mako.template下的Template类。
#coding: utf-8 from mako import template class DMTemplate(template.Template): def render(self, context): # flatten the Django Context into a single dictionary. context_dict = {} for d in context.dicts: context_dict.update(d) return super(DMTemplate, self).render(**context_dict) setattr(template, 'Template', DMTemplate)
然后在项目路径下新建一个文件django_mako.py。
#coding: utf-8 from mako.lookup import TemplateLookup from django.template.loaders import app_directories import settings mylookup = TemplateLookup( directories = settings.TEMPLATE_DIRS, module_directory = '/tmp/mako_modules', input_encoding = 'utf-8', output_encoding = 'utf-8', encoding_errors = 'replace', format_exceptions = True, ) class Loader(app_directories.Loader): is_usable = True def load_template(self, template_name, template_dirs=None): _template = mylookup.get_template(template_name) return _template, _template.source
然后修改settings.py,使用刚定义好的loader。
TEMPLATE_LOADERS = ( # 'django.template.loaders.filesystem.load_template_source', # 'django.template.loaders.app_directories.load_template_source', 'myblog.django_mako.Loader', )
这样就可以在django1.2下使用mako模板了。
😊 如果你喜欢这篇文章,也欢迎了解我的书: 《Python 工匠:案例、技巧与工程实践》 。它专注于编程基础素养与 Python 高级技巧的结合,是一本广受好评、适合许多人的 Python 进阶书。