You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 04:26:55