在某些页面上,我希望我的表单下拉按特定顺序排列,而在其他页面中按默认顺序排列。当从我的应用传递特定顺序时,我在 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.html
。 When 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) }}
关于python - Jinja 宏看不到传递给 render_template 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30738029/