python - Jinja 宏看不到传递给 render_template 的值

标签 python flask jinja2

在某些页面上,我希望我的表单下拉按特定顺序排列,而在其他页面中按默认顺序排列。当从我的应用传递特定顺序时,我在 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. dropdownview.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) }}

关于python - Jinja 宏看不到传递给 render_template 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30738029/

相关文章:

java - 0xaa 和 0x55 在做什么?

python - 如何使用 Python 构建基于时间戳发生的序列?

python - 无法访问instancemethod属性?

anchor - 在 werkzeug 请求中检索 url anchor

Python UnicodeDecodeError : 'utf8' codec can't decode byte. ..意外的代码字节

python - 如何提取特定单词周围的文本片段?

python - 使用 Python + Flask-SqlAlchemy 的默认查询范围

python - Flask发送html数据回 View

ansible - 如何在 JMESPath 中使用 if/else 条件

python - 在Python中读取Jinja文件