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

如何在Django模板的单个for循环中获取对应列表数据?

问题解决方法

你当前模板里的{{min_temperature.i}}写法不符合Django模板语法,Django不支持通过.加索引来访问列表元素,下面提供几种可行方案:

方案1:直接遍历列表(推荐)

不需要在context里传递range变量,直接遍历min_temperature列表本身:

{% for temp in min_temperature %}
  <p>{{ temp }}</p>
{% endfor %}

如果需要同时获取索引,可使用模板内置的forloop.counter0(从0开始计数)或forloop.counter(从1开始计数):

{% for temp in min_temperature %}
  <p>第{{ forloop.counter0 }}个时段最低温:{{ temp }}</p>
{% endfor %}

方案2:自定义模板过滤器(适配原range循环)

如果坚持要用自己传递的range变量循环,需要自定义模板过滤器实现列表索引访问:

  1. 在你的Django应用下创建templatetags目录(无则新建),并添加__init__.py和custom_filters.py文件:
# your_app/templatetags/custom_filters.py
from django import template

register = template.Library()

@register.filter
def get_item(lst, index):
    return lst[index]
  1. 在模板中加载过滤器并使用:
{% load custom_filters %}

{% for i in range %}
  <p>{{ min_temperature|get_item:i }}</p>
{% endfor %}

额外优化:同时处理最低温和最高温

如果需要在同一循环里获取对应位置的最低温和最高温,建议在视图层将两个列表打包,简化模板逻辑:
修改views.py的context:

context={
    'min_temperature': [np.min(today['temperature_2m'][i:i+3]) for i in range(0,24,3)],
    'max_temperature': [np.max(today['temperature_2m'][i:i+3]) for i in range(0,24,3)],
    # 新增打包后的列表
    'temp_pairs': zip(
        [np.min(today['temperature_2m'][i:i+3]) for i in range(0,24,3)],
        [np.max(today['temperature_2m'][i:i+3]) for i in range(0,24,3)]
    ),
    # 其他变量...
}

模板中直接遍历打包后的元组:

{% for min_temp, max_temp in temp_pairs %}
  <p>时段最低温:{{ min_temp }},最高温:{{ max_temp }}</p>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:44:58