有没有办法把变量传递给Jinja2的父母?

2024-06-01 03:42:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一些变量从子页传递到模板。这是我的python代码:

    if self.request.url.find("&try") == 1:
        isTrying = False
    else:
        isTrying = True

    page_values = {
        "trying": isTrying
    }

    page = jinja_environment.get_template("p/index.html")
    self.response.out.write(page.render(page_values))

模板:

<html>
  <head>
    <link type="text/css" rel="stylesheet" href="/css/template.css"></link>
    <title>{{ title }} | SST QA</title>

    <script src="/js/jquery.min.js"></script>

  {% block head %}{% endblock head %}
  </head>
  <body>
    {% if not trying %}
    <script type="text/javascript">
    // Redirects user to maintainence page
    window.location.href = "construct"
    </script>
    {% endif %}

    {% block content %}{% endblock content %}
  </body>
</html>

孩子们:

{% extends "/templates/template.html" %}
{% set title = "Welcome" %}
{% block head %}
{% endblock head %}
{% block content %}
{% endblock content %}

问题是,我想把变量“trying”传递给父对象,有没有办法做到这一点?

提前谢谢!


Tags: self模板iftitlehtmlpagescripttemplate
2条回答

我不明白你的问题。当您将变量传递到上下文时(就像您尝试的那样),这些变量将在子和父中可用。 若要将标题传递给父项,必须使用继承,有时还需要结合使用super:http://jinja.pocoo.org/docs/templates/#super-blocks

另见这个问题:Overriding app engine template block inside an if

Jinja2技巧页面上的示例完美地解释了这一点,http://jinja.pocoo.org/docs/templates/#base-template。基本上,如果你有一个基本模板

**base.html**
<html>
    <head>
        <title> MegaCorp -{% block title %}{% endblock %}</title>
    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
    </body>
</html>

以及子模板

**child.html**
{% extends "base.html" %}
{% block title %} Home page {% endblock %}
{% block content %}
... stuff here
{% endblock %}

无论python函数调用什么render_template(“child.html”)都将返回html页面

**Rendered Page**
<html>
    <head>
        <title> MegaCorp - Home </title>
    </head>
    <body>
        <div id="content">
            stuff here...
        </div>
    </body>
</html>

相关问题 更多 >