如何在 Jinja2 中将变量从一个模板传递到另一个模板

How to pass variables from one template to another in Jinja2

如标题所述,我关心的是如何将 parent Jinja2 模板中的变量集传递给它的 child 模板。

项目配置如下:

不幸的是,当我尝试执行上述过程时,child.html 没有从 parent.py 中找到 response

这是一个代码片段:

app.py

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/parent', ParentHandler),
            (r'/child', ChildHandler)
        ]

        jinja_load = Jinja2Loader(os.path.join(PATH, '/templates'))
        settings = {
            'template_path': os.path.join(PATH, '/templates')
            'template_loader': jinja_load
        }
        tornado.web.Application.__init__(self, handlers, **settings)

parent.py

class ParentHandler(tornado.web.RequestHandler):
    def get(self):
        response = {"status": "200", "val": "some_value"}
        try:
            self.render("parent.html", response=response)
        except:
            self.write(response)

child.py

class ChildHandler(tornado.web.RequestHandler):
    def get(self):
        response = {"status": "200", "data": "some_data"}
        try:
            self.render("child.html", child_content=response)
        except:
            self.write(response)

parent.html

<div>
    {% if response['status'] == 200 %}
        {% set val1 = response.get('val', 0) %}
        <i>{{ val1 }}</i>
    {% endif %}
</div>
{% block child_content %}{% endblock %}

child.html

{% include 'parent.html' %} 
{% from 'parent.html' import val1 %} 
{% block child_content %}
<table>
{% for d in data %}
    <tr>
        <td>{{ d }}</td>
    </tr>
{% endfor %}
{% endblock %}

但是我在尝试渲染时遇到了这个错误 child.html:

UndefinedError: 'response' is undefined

有人能帮帮我吗?

你只需要在 include 语句中添加 with 关键字,如下所示:

{% include 'parent.html' with var1=value1, var2=value2, ... %} 

你的情况

{% include 'parent.html' with response=responseValue %} 

我最终放弃了最初的想法,决定采用@Strinnityk 的解决方案。 我更改了 child.py 的输出并使用 parent.py 的输出更新了它。 这样,我什至不需要在 child.html 模板中使用变量。

再次感谢!