简单体验python mako

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

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

sudo pip install Mako
sudo pip install django-mako


[b]2. 一个简单的例子[/b]

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()


[b]3. 基于文件的Templates[/b]
上面的例子中,Template是通过字符串的方式构建的,下面将介绍通过文件:
from mako.template import Template

mytemplate = Template(filename='/docs/mytmpl.txt')
print mytemplate.render()


[b]4. 语法[/b]

[b]a. 表达式,和jsp,velocity很像:[/b]
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将被解析成: <tag>some value</tag> 更多: http://docs.makotemplates.org/en/latest/filtering.html

[b]b. 流程控制[/b]


% if x==5:
this is some output
% endif

% for a in ['one', 'two', 'three', 'four', 'five']:
% if a[0] == 't':
its two or three
% elif a[0] == 'f':
four/five
% else:
one
% endif
% endfor



[b]c. python block:[/b]

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

更多参考:http://docs.makotemplates.org/en/latest/syntax.html

[b]5. 最后说说和django集成问题[/b]

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/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python Mako是一个模板引擎,用于生成动态HTML、XML、CSV或任何其他文本格式的输出。它基于Python语言,类似于Jinja2和Django模板引擎,但它使用了一种不同的语法和一些特殊的功能。 Mako提供了一个简单而强大的模板系统,使开发人员可以轻松地将模板嵌入到应用程序中,以便动态生成内容。它具有模板继承、过滤器、块标记等高级功能,使开发人员能够更轻松地组织和重用模板代码。 以下是一个使用Mako简单示例: ```python from mako.template import Template # 定义模板 mytemplate = Template("Hello ${name}!") # 渲染模板 print(mytemplate.render(name="World")) ``` 输出: ``` Hello World! ``` 在上面的示例中,我们定义了一个简单的模板,它包含一个变量`${name}`。我们还使用`render()`方法将模板渲染为字符串,并传递一个名为`name`的变量。 Mako还支持模板继承。这使得开发人员可以定义一个基本模板,并在派生模板中重写或扩展它。以下是一个使用模板继承的示例: ```python # 定义基本模板 base_template = Template(""" <html> <head> <title>${title}</title> </head> <body> ${body} </body> </html> """) # 定义派生模板 derived_template = Template(""" <%inherit file="base_template"/> <%block name="body"> <h1>${title}</h1> <p>${content}</p> </%block> """) # 渲染派生模板 print(derived_template.render(title="My Page", content="Welcome to my page!")) ``` 在上面的示例中,我们定义了一个基本模板`base_template`,它定义了一个HTML文档的基本结构。然后,我们定义了一个派生模板`derived_template`,它通过`inherit`指令继承了基本模板,并重写了`body`块。最后,我们使用`render()`方法渲染派生模板,并传递`title`和`content`变量。 这只是Mako的一些基础功能,还有很多其他功能可以探索。如果您想学习更多,请查看Mako的官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值