Jinja2字典赋值报错:expected token 'end of statement block', got '='
Jinja2字典赋值报错:expected token 'end of statement block', got '='
你遇到的错误是因为{% do dic[seq_key]=filter %}不符合Jinja2的语法规范——do语句仅支持执行表达式,不能直接使用赋值运算符=为字典键赋值。
修复方案
使用字典的update()方法来添加键值对,这是Jinja2中修改字典的标准方式:
{% set sequence = ['a1', 'b1']%} {% set dic = {} %} {% for filter in search_result.filters %} {% for seq_key in sequence %} {% if seq_key == filter.key %} {# 通过update方法向字典添加键值对 #} {% do dic.update({seq_key: filter}) %} {% endif %} {% endfor %} {% endfor %}
补充说明
如果你的Jinja2环境未默认启用do语句扩展,需要先在环境配置中添加jinja2.ext.do扩展(多数基于Jinja2的框架如Flask已默认开启)。
Jinja2对模板内的赋值操作有严格限制,直接修改字典键不能用常规赋值语法,必须通过表达式化的方法(如字典内置的update())来实现。
内容的提问来源于stack exchange,提问作者puranjan
相关产品推荐
相关产品推荐

