Mako是Pylons的默认采用的模板,很简洁,也很强大。对于初次接触Mako的朋友来说可能会觉得Mako的Namespace很奇特,熟悉Jsp的会觉得和Jsp等大不一一样,不过要是接触过Django,写过Django的template,用过{% block %}{% endblock %}操作的话,应该很快就能熟悉Mako的Namespace。但Mako中的Namespace和Django的block还是很很大的不同的。本文着重讲述一下Mako中的基本Namespace的操作。
Mako中常用的Namespace有local、self、parent、next,其中:
local:指向当前执行的template
self:对于没有使用inheritance的template来说,self等同于local;但如果使用了inheritance,self指向inheritance chain的最顶层(the topmost template)
parent:指向当前template的直接上一级template(immediately preceding),Mako中的parent有点儿类似于python中的super
next:指向当前template的直接下一级template(immediately following)
下面举一例子对上述几个namespace做一说明:
(1)创建base.html
## base.html
<html>
<body>
<div class="header">
<%block name="header"/>
</div>
${next.body()}
<div class="footer">
<%block name="footer">
this is the footer
</%block>
</div>
</body>
</html>
(2)创建layout.html
## layout.html
<%inherit file="base.html"/>
<ul>
<%block name="toolbar">
<li>selection 1</li>
<li>selection 2</li>
<li>selection 3</li>
</%block>
</ul>
<div class="mainlayout">
${next.body()}
</div>
(3)创建index.html
## index.html
<%inherit file="layout.html"/>
<%block name="header">
this is some header content
</%block>
<%block name="toolbar">
## call the parent's toolbar first
${parent.toolbar()}
<li>selection 4</li>
<li>selection 5</li>
</%block>
this is the body content.
(4)此时整个inheritance chain示意图为 base.html --> layout.html --> index.html
此时index.html的实际内容应该为:
<html>
<body>
<div class="header">
this is some header content
</div>
<ul>
<li>selection 1</li>
<li>selection 2</li>
<li>selection 3</li>
<li>selection 4</li>
<li>selection 5</li>
</ul>
<div class="mainlayout">
this is the body content.
</div>
<div class="footer">
this is the footer
</div>
</body>
</html>

浙公网安备 33010602011771号