在Jinja2中为循环动态创建变量

时间:2019-01-20 17:15:00

标签: python html flask jinja2

在for循环中,我遍历字典列表,如果满足某些条件,则为新变量分配特定字典键的值。如果该变量存在,则希望将其值分配给输入字段。示例如下:

{% for month in months %}

{% for value in values %}
    {% if value.condition_1 == 'Condition1' %}
        {% if value.condition_2 == 'Condition2' %}

             {% {{ month }}_value_present = value.month_value %}      <<< This line here

        {% endif %}
    {% endif %}
{% endfor %}

{% if {{ month }}_value_present %}     <<< This line here
    <input type="text" name="value_weighting_{{ month }}" class="modal-month-boxes" value="{{ {{ month }}_value_present }}">
{% else %}
    <input type="text" name="value_weighting_{{ month }}" class="modal-month-boxes">
{% endif %}

{% endfor %}

此方法会产生以下错误,该错误是由{{ month }}标记引起的:

  

jinja2.exceptions.TemplateSyntaxError:期望标记名称

以这种方式动态创建变量的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

{% if {{ month }}_value_present %}失败,因为解析令人窒息。尝试使用制作字符串变量,然后使用locals()getattr来访问该值的做法有些骇人?