【问题标题】:Pass variable from called Mako template to inherited template将变量从被调用的 Mako 模板传递给继承的模板
【发布时间】: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.titleparent.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 标签的属性。

标签: python cherrypy mako


【解决方案1】:

为了使用呈现的变量 - 您将它们与 ${ title } 一起使用,而不是 $( title )

【讨论】:

    猜你喜欢
    • 2011-05-08
    • 2011-12-26
    • 2011-08-24
    • 2013-06-25
    • 2010-12-22
    • 2017-11-10
    • 2012-10-14
    • 2021-09-27
    • 2016-02-16
    相关资源
    最近更新 更多