从Jinja2的超级块访问变量

问题描述 投票:0回答:1

我正在尝试设计具有主要模板的多节报告文档:

<html>
  <body>
    {% include "SectionA.html" %}
    {% include "SectionB.html" %}
    ...
  </body>
</html>

[每个包含的SectionX.html文件在其中扩展base.html文件的位置。

我想让base.html设置一系列变量(用于控制流),这些变量可以在SectionX.html文件中覆盖。我试图用setVariables块来完成此操作,但这不起作用。

我的base.html文件看起来像:

{% block setVariables %}
{% set doFoo = False %}
{% set doBar = False %}
{% set bazValues = [] %}
{% endblock setVariables %}

{% if doFoo %}
...

然后覆盖每个扩展文件中的该部分:

{% block setVariables %}
{% set doFoo = sectionFoo %}
{% set doBar = sectionBar %}
{% set bazValues = sectionBaz %}
{% endblock setVariables %}

问题是,doFoo被设置在两个完全独立的范围内,而我还没有找到一种方法来访问另一个。我不确定是否可以使用当前的策略来解决此问题,但是我很感谢能帮助您创建此模块化,多部分报告的任何方法。

python html inheritance scope jinja2
1个回答
0
投票

您可以改用include标记在当前名称空间中呈现include的内容。

因此base.html应该只为公共变量设置默认值:

base.html

然后在每个单独的HTML文件中:

{% set doFoo = False %}
{% set doBar = False %}
{% set bazValues = [] %}
© www.soinside.com 2019 - 2024. All rights reserved.