繁体   English   中英

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

[英]Is there a way to pass variables into Jinja2 parents?

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

    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”传递给父级,有没有办法做到这一点?

提前致谢!

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 %}

任何调用 render_template("child.html") 的 python 函数都会返回 html 页面

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

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

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

然后使用可以在 base.html 中使用“active”

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

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

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

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

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

另见这个问题: Overriding App Engine template block inside an if

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM