![在Django中使用Mako模板 在Django中使用Mako模板](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
用了一个月后,终于忍受不了Django的模板了。主要原因是模板内不能运行原生的python语句,所以用起来总感觉被人绑住手脚,遍历个字典都要搞半天。
所以决定用第三方的模板。查了一下,django用的第三方模板中,性能较好的是mako和jinja2。看了它们的语法后,发现mako会更为简洁,所以选择了mako。
1.安装
安装mako,使用 pip install Mako 命令 安装mako
安装django-mako 下载https://pypi.python.org/pypi/django-mako 然后用命令 python setup.py install 安装
有时安装会一直停在Reading http://pypi.python.org/simple/MyghtyUtils/,这是已经安装成功,直接ctrl+c关闭进程即可
2.在项目的setting.py文件所在的目录下新建一个mymako.py
#mymako.py
from django.template.context import Context
from django.http import HttpResponse
from mako.template import Template
from mako.lookup import TemplateLookup
import os def render_to_response(t,c=None,context_instance=None):
path = os.path.join(os.path.dirname(__file__), 'template/')
mylookup = TemplateLookup(directories=[path],output_encoding='utf-8')
mako_temp = mylookup.get_template(t)
if context_instance:
context_instance.update(c)
else:
context_instance = Context(c)
data = {}
for d in context_instance:data.update(d)
return HttpResponse(mako_temp.render(**data))
path参数是模板所在的目录
3.在views中调用
def test(request): from mymako import render_to_response
return render_to_response("test1.html",{"name":"kevin"})
4.mako模板中的继承
index.html
## index.html
<%inherit file="base.html"/> <%def name="body()">
some html code
</%def>
base.html
## base.html
<html>
<body>
<div class="header">
hello
</div> ${self.body()} <div class="footer"> </div>
</body>
</html>
5.python语句
<div id="read">
% for key in result_dict: <p>
<b>${key_ench[key]} </b> : ${result_dict[key]}
</p>
% endfor
<p>
<b>服务器 </b> : ${server_role}
</p> </div>
6.包含一个HTML文件
<%include file="metric_header.html",args="realtime_server_conf=realtime_server_conf" />
参考资料:
http://duka.iteye.com/blog/634208
http://www.sandzhang.com/blog/2010/04/03/install-mako-templates-and-plugin-for-django/
DEBUG
以前
1.在mako模板中,python块<% %>要放在 def里面,不然会弹出“undefined"错误,例如变量的定义 a='aa'
2.当模板报错 <mako.runtime.Undefined object at 0x2edd750> 时是因为模板中存在没定义的变量
3.当模板报错 Undefined 时是因为模板中存在没定义的变量
10-17
报错
(IndentationError) expected an indented block (line ) ('for key in result_dict:\rpass') in file '/data/web/mcyw/mcyw_web/mcyw_web/template/cmdb_server_report1.html' at line: char:
原因是使用了pycharm新建一个html文件,可能是pycharm新建的文件有问题,每一行都加了\rpass,所以模版报错,复制一个原谅的html文件,然后再上面修改就没有问题了