读书人

简略体验python mako

发布时间: 2012-06-25 21:24:50 作者: rapoo

简单体验python mako
django自带的模板用着不爽,准备替换成python Mako,这也是豆瓣使用的模板语言。

1. 环境准备
直接使用pip,如果不知道什么是pip,会死的很惨

sudo pip install Mako
sudo pip install django-mako


2. 一个简单的例子


| 后面这个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通过逗号间隔:

上面这段code将被解析成: <tag>some value</tag> 更多: http://docs.makotemplates.org/en/latest/filtering.html

b. 流程控制
from djangomako.shortcuts import render_to_responsedef 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/

读书人网 >perl python

热点推荐