Based on AssertionError: Tried to resolve a name to a reference that was unknown to the frame this problem is only in Jinja2
versions 3.x
. Older versions 2.x
works correctly.
At this moment it needs to set variable before you use it in block. Maybe later they fix it.
{% set item = None %}
{% set stuff %}
{% for item in items %}
<p>{{item}}</p>
{% endfor %}
{% endset %}
{{ stuff }}
But set
has one big drawback for me: it can't get arguments and it works only with items
.
And it can't works if I set {% set items = other_items %}
I would rather put code in macro
to use stuff(main_items)
, stuff(other_items)
, etc.
{% macro stuff(items) %}
{% for item in items %}
<p>{{item}}</p>
{% endfor %}
{% endmacro %}
{{ stuff(main_items) }}
{{ stuff(other_items) }}
Minimal working code:
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string('''
<h1>SET</h1>
{% set item = None %}
{% set stuff_set %}
{% for item in items %}
<p>{{item}}</p>
{% endfor %}
{% endset %}
{{ stuff_set }}
<h1>MACRO</h1>
{% macro stuff_macro(items) %}
{% for item in items %}
<p>{{item}}</p>
{% endfor %}
{% endmacro %}
{{ stuff_macro(main_items) }}
{{ stuff_macro(other_items) }}
''', items=['A', 'B', 'C'], main_items=[1,2,3], other_items=[4,5,6])
if __name__ == '__main__':
#app.debug = True
app.run()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…