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

时间:2013-01-10 09:15:13

标签: python html google-app-engine jinja2

我正在尝试将一些变量从子页面传递给模板。这是我的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 %}

问题是,我想将变量“尝试”传递给父级,有没有办法做到这一点?

提前致谢!

4 个答案:

答案 0 :(得分:16)

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>

答案 1 :(得分:1)

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

组合使用

另请参阅此问题:Overriding app engine template block inside an if

答案 2 :(得分:1)

我认为您希望突出显示基本布局中的活动菜单,并且您需要类似的东西

{% extends 'base.html' %}
{% set active = "clients" %}

然后可以在base.html内使用“活动”

答案 3 :(得分:1)

您只需要在扩展模板之前声明该变量,这样扩展模板就可以访问变量trying

{% set trying = True %}  <----------- declare variable

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

几年后但希望它可以帮助后来者

相关问题