mako模板调试与使用技巧

django默认的模板太不灵活,想把一个数字0.15显示成15%都得费不少劲,太不爽!!!

网上查阅了几个模板系统,有Jinja2等等,最后发现mako能够直接支持python的语句,最为灵活,果断选用。

使用过程中碰见的问题不少,记录如下:

1. 调试技巧:如果在mako的模板显示过程中出现问题,django的错误提示就一个字,“错”,剩下的,慢慢查吧,然后我挨个删除,挨个尝试,就一个惨字了得。弄了几个错误之后崩溃了。最后在stackoverflow上面找到了解决办法,代码如下:

from mako.lookup import TemplateLookup
from mako import exceptions
risk_lookup = TemplateLookup(
directories=risk_platform.settings.TEMPLATE_DIRS,
input_encoding='utf-8',
output_encoding='utf-8',
default_filters=['none_empty', 'h', ],
imports=['from risk.views import none_empty'],
)


def render_to_response(filename, ctx):
try:
tp = risk_lookup.get_template(filename)
cont = tp.render(**ctx)
return http.HttpResponse(cont)
except :
return http.HttpResponse(exceptions.html_error_template().render())

一旦在render的过程中出现异常,使用mako展示错误的方式来输出。一下天清气朗。

2. moko中的for循环使用的变量会覆盖context中的变量,因此如下的模板代码无法正常运行:

% for name in names:

  <td>${name}</td>

% end for

<tr>${name}</td>

后面的这个${name}就无法获取到context里面的相关变量值了。目前我也没有时间去查阅相关资料了,等有时间了在慢慢看吧。

3. djangomako这个包根本就无法使用,一运行就错了(我的版本是python3.4 django_mako-0.1.3)看了看源代码,就两三行有用的,干脆就不用他这个包了


posted on 2015-06-19 16:49  dongfuye  阅读(1455)  评论(0编辑  收藏  举报

导航