a6266318 发表于 2017-4-23 14:08:15

简单体验python mako

django自带的模板用着不爽,准备替换成python Mako,这也是豆瓣使用的模板语言。
1. 环境准备
直接使用pip,如果不知道什么是pip,会死的很惨
sudo pip install Mako
sudo pip install django-mako

2. 一个简单的例子

from mako.template import Template
mytemplate = Template("hello world!")
print mytemplate.render()

和java的模板系统大同小异,加上context:
from mako.template import Template
mytemplate = Template("hello, ${name}!")
print mytemplate.render(name="jack")

这里render方法会自动创建Context对象,也可以自己创建Context:

from mako.template import Template
from mako.runtime import Context
from StringIO import StringIO
mytemplate = Template("hello, ${name}!")
buf = StringIO()
ctx = Context(buf, name="jack")
mytemplate.render_context(ctx)
print buf.getvalue()


3. 基于文件的Templates
上面的例子中,Template是通过字符串的方式构建的,下面将介绍通过文件:
from mako.template import Template
mytemplate = Template(filename='/docs/mytmpl.txt')
print mytemplate.render()

4. 语法
a. 表达式,和jsp,velocity很像:
this is x: ${x}
但比velocity智能,数学运算很方便有木有:
${pow(x,2) + pow(y,2)}
the contents within the ${} tag are evaluated by Python directly, so full expressions are OK.
还有比java先进的,看看这个:
${"this is some text" | u}
| 后面这个u是什么意思?
Mako 内置了多个escaping filter ,包括 HTML, URL, XML escaping,trim(),这些filter可以通过| 后面跟表达式来表示。
    u : URL escaping, provided by urllib.quote_plus(string.encode('utf-8'))
    h : HTML escaping, provided by markupsafe.escape(string)
    x : XML escaping
    trim : whitespace trimming, provided by string.strip()
    entity : produces HTML entity references for applicable strings, derived from htmlentitydefs
    unicode (str on Python 3): produces a Python unicode string (this function is applied by default)
    decode.<some encoding> : decode input into a Python unicode with the specified encoding
    n : disable all default filtering; only filters specified in the local expression tag will be applied.
多个filter通过逗号间隔:
${" <tag>some value</tag> " | h,trim}
上面这段code将被解析成: &lt;tag&gt;some value&lt;/tag&gt; 更多: http://docs.makotemplates.org/en/latest/filtering.html
b. 流程控制

% if x==5:
this is some output
% endif
% for a in ['one', 'two', 'three', 'four', 'five']:
% if a == 't':
its two or three
% elif a == 'f':
four/five
% else:
one
% endif
% endfor


c. python block:

this is a template
<%
x = db.get_resource('foo')
y =
%>
% for elem in y:
element: ${elem}
% endfor

更多参考:http://docs.makotemplates.org/en/latest/syntax.html
5. 最后说说和django集成问题
1)在你django项目的settings.py中的MIDDLEWARE_CLASSES里增加一项djangomako.middleware.MakoMiddleware例:

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'djangomako.middleware.MakoMiddleware',
)

添加django方法,例:

from djangomako.shortcuts import render_to_response
def hello_view(request):
return render_to_response('hello.html', {'name':'sand'})

启动你的django项目,浏览器访问一下http://yourhostname/hello,看下是不是看到返回的hello sand!

http://www.sandzhang.com/blog/2010/04/03/install-mako-templates-and-plugin-for-django/
页: [1]
查看完整版本: 简单体验python mako