【发布时间】:2013-05-14 10:53:26
【问题描述】:
我正在使用带有 Mako 模板的 CherryPy。我正在尝试研究如何从初始调用中传递参数(在此示例中为 title):
class Landing(object):
def index(self):
tmpl = lookup.get_template("index.html")
return tmpl.render(title="Hello World")
index.exposed = True
致index.html:
<%inherit file="base.html"/>
<%def name="title()">$(title)</%def>
this is the body content
然后到继承的base.html模板:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>$(self.title())</title>
</head>
<body>
<h1>$(parent.title())</h1>
${self.body()}
</body>
</html>
我试过self.title 和parent.title 都没有工作。如何从初始调用中传递变量?
【问题讨论】:
-
${title} 应该可以。因此,请使用大括号而不是常规括号。而且它不是函数调用,所以去掉最后的()。
-
您可能还想将 name="title()" 更改为 name="${title}"
-
@basvandenberg 谢谢,就是这样!如果您将其添加为答案,我会接受。我尝试用 ${title} 替换 title() 但出现错误:
mako.exceptions.CompileException: Attibute 'name' in tag 'def' does not allow embedded expressions in file 'template/index.html' at line: 2 char: 1 -
抱歉,我没有看到 'name' 属性在 mako 标记中,而不是在常规的 html 标记中。我不确定您是否可以使用变量来设置 mako 标签的属性。