Django1.2下使用mako模板

Type: 技术相关 - Posted at: 2010/07/27 23:53

看完了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模板了。

<
>
1# 棉花糖   said this at 2010-07-28 06:28 : [Quote]
我不在的时候你比以前勤奋
2# Admin   said this at 2010-07-28 09:17 : [Quote]
Quoted 棉花糖:

我不在的时候你比以前勤奋


没啦,只是现在想记录点东西下来而已。
3# 树根   said this at 2010-12-01 02:06 : [Quote]
你这么设置是不是为了解决mako的中文编码问题?
4# Admin   said this at 2010-12-01 20:21 : [Quote]
Quoted 树根:

你这么设置是不是为了解决mako的中文编码问题?


这样是为了在django中使用mako模板,不知道你碰到了什么样的编码问题呢?
5# 树根   said this at 2010-12-02 20:34 : [Quote]
Quoted 树根:

你这么设置是不是为了解决mako的中文编码问题?

Quoted Admin:

这样是为了在django中使用mako模板,不知道你碰到了什么样的编码问题呢?


我遇到的问题是mako的字符编码问题,中文问题总是无法解决
6# 灰灰   said this at 2010-12-03 14:43 : [Quote]
Quoted Admin:

这样是为了在django中使用mako模板,不知道你碰到了什么样的编码问题呢?

show all quoted

Quoted 树根:

我遇到的问题是mako的字符编码问题,中文问题总是无法解决


貌似 要在 html模板页面 加一个 coding:utf-8
不知道 你遇到是不是这种问题
7# 树根   said this at 2010-12-07 14:03 : [Quote]
Quoted 树根:

我遇到的问题是mako的字符编码问题,中文问题总是无法解决

show all quoted

Quoted 灰灰:

貌似 要在 html模板页面 加一个 coding:utf-8
不知道 你遇到是不是这种问题


我已经加了coding:utf8了,但是问题依旧
8# Insion   said this at 2011-03-20 12:22 : [Quote]
你这个网站是用python写的?空间在哪里买的?想买个python的空间呢~
Name:  *   Remember me
E-mail:  *  Not public, supported by Gravator
Website:      Not required
Question:
4 * 0 = *
Content: