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

如何在Django模板中获取列表索引并关联其他列表值?

Django模板中根据变量索引获取列表元素的解决方法

方法一:视图层预处理数据(推荐)

把需要对应展示的数据打包成元组或字典,直接传入模板循环,模板只需负责展示,逻辑更清晰。

修改views.py的上下文:

# 处理问题1:将item1、item2、item3按索引对应打包(处理长度不一致,超出部分补空)
combined_items = list(zip(item1[:5], item2, item3)) + list(zip(item1[5:], ['']*5, ['']*5))
# 处理问题2:将item6和item2打包
combined_item6_item2 = list(zip(item6, item2))

context.update({
    'combined_items': combined_items,
    'combined_item6_item2': combined_item6_item2
})

对应模板写法:
问题1模板:

{% for num, val2, val3 in combined_items %}
<td> {{ num }} </td>
<td> {{ val2 }} </td>
<td> {{ val3 }} </td>
{% endfor %}

问题2模板:

{% for num, val2 in combined_item6_item2 %}
<td> {{ item2.0 }} </td>
<td> {{ val2 }} </td>
{% endfor %}

方法二:自定义模板过滤器

如果不想修改视图层,可以自定义过滤器实现按变量索引取列表元素。

  1. 在你的app目录下创建templatetags文件夹,新建__init__.py和custom_filters.py文件。
  2. 在custom_filters.py中编写过滤器:
from django import template

register = template.Library()

@register.filter
def get_item(lst, index):
    try:
        return lst[index]
    except (IndexError, TypeError):
        return ''
  1. 在模板顶部加载过滤器:
{% load custom_filters %}

对应模板写法:
问题1模板(用forloop.counter0获取循环的0起始索引):

{% for num in item1 %}
<td> {{ num }} </td>
<td> {{ item2|get_item:forloop.counter0 }} </td>
<td> {{ item3|get_item:forloop.counter0 }} </td>
{% endfor %}

问题2模板:

{% for num in item6 %}
<td> {{ item2.0 }} </td>
<td> {{ item2|get_item:num }} </td>
{% endfor %}

注意事项

  • 当循环列表与目标列表长度不一致时,要处理索引越界问题,自定义过滤器中已通过异常处理返回空字符串避免报错。

内容的提问来源于stack exchange,提问作者Nod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:12:56