Jinja 宏看不到传递给 render_template 的值

Jinja macro doesn't see value passed to render_template

在某些页面上,我希望我的表单下拉按特定顺序排列,而在其他页面中按默认顺序排列。从我的应用程序传递特定顺序时,我在 form.html 中的宏似乎看不到它。 dropdown 从未使用过,模板始终显示全局数据。为什么会这样?

form.html:

    {% if dropdown %}
        <select name="status">
        {% for option in dropdown %}
              <option value="{{ option }}">{{ option }}</option>
        {% endfor %}
        </select>
    {% else %}
        <select name="status">
        {% for option in global_add_links_data()[0] %}
              <option value="{{ option }}">{{ option }}</option>
        {% endfor %}
        </select>
    {% endif %}

app.py:

dropdown = [
    'Placed',
    'Review Not Started',
    'Review Passed',
    'Review Failed',
    'Contacted Pending',
    'Contacted Failed',
    'No Contacts',
    'No Reply',
    'Not Interested'
]
dropdown.insert(0, dropdown.pop(dropdown.index(link_status)))
return render_template('view.html', dropdown=dropdown)

您没有直接渲染 form.html,您正在渲染 view.html 并导入 form.htmlWhen importing other templates, the template context is not passed by default. dropdown 局部于 view.html 上下文,因此在 form.html.

中始终未定义

要导入带有上下文的模板,请使用 with context 关键字。

{% from "form.html" render_form with context %}

更好、更明确的处理方法是将 dropdown 作为参数传递给宏。这样效率更高,因为正如上面的文档所述,导入通常会缓存以提高性能,但是使用 with context 会禁用它。

{% macro render_form(form, dropdown=None) -%}
    {% if dropdown %}
    {% else %}
    {% endif %}
{%- endmacro %}
{% from "form.html" import render_form %}
{{ render_form(form, dropdown) }}