簡體   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