Django模板中如何通过索引获取字典列表的price值?
嘿,这个问题我之前也碰到过,马上帮你理清思路!
首先得说清楚你为啥会报错:你写的{{i.item|index:forloop.counter0.price}}逻辑走偏了——模板引擎会把forloop.counter0.price当成传给index过滤器的参数,但forloop.counter0就是个普通整数(循环的起始索引),它根本没有price属性,所以才会抛出“invalid key price at index 0”的错误。
正确的思路是:先用index过滤器拿到目标字典对象,再去访问它的price键。下面给你两种靠谱的解决方案:
方案1:用{% with %}标签临时存字典(最推荐)
这种方式清晰直观,还能处理列表长度不一致的情况(避免索引越界后报错):
{% for _ in longest_list %} {% with current_item=i.item|index:forloop.counter0 %} {% if current_item %} {# 直接输出price值 #} {{ current_item.price }} {% else %} {# 如果当前索引超出列表长度,显示默认值或者空 #} 0.00 {% endif %} {% endwith %} {% endfor %}
{% with %}标签会先执行i.item|index:forloop.counter0拿到字典,然后把它存在current_item变量里,之后你就可以安全地访问current_item.price了。
方案2:修改自定义过滤器,直接返回price值
如果你不想用with标签,也可以扩展一下你的index过滤器,让它支持直接提取字典的键值。比如在你的模板过滤器文件里新增一个过滤器:
from django import template register = template.Library() # 原来的index过滤器 @register.filter def index(lst, idx): try: return lst[int(idx)] except (IndexError, TypeError, ValueError): return None # 新增的过滤器:根据索引和键获取值 @register.filter def index_get(lst, args): # 把参数拆成索引和键,比如传入"0,price" idx_str, key = args.split(',') try: item = lst[int(idx_str.strip())] return item.get(key.strip(), None) except (IndexError, TypeError, ValueError): return None
然后在模板里这样用:
{{ i.item|index_get:forloop.counter0|stringformat:"d"|add:",price" }}
不过这种方式不如第一种直观,维护起来也稍麻烦,所以更推荐方案1。
内容的提问来源于stack exchange,提问作者Syntax_Error
相关产品推荐
相关产品推荐

