You need to enable JavaScript to run this app. Django模板for循环如何通过counter按轮次获取连续数值
优惠活动
大模型
产品
解决方案
定价
更多

Django模板for循环如何通过counter按轮次获取连续数值

实现方案

核心逻辑

你可以直接利用Django模板自带的forloop.counter(从1开始自动计数当前循环轮次)推导需要的两个数值:

  • 每轮的第一个ID(编辑操作对应的折叠容器):2 * 当前循环轮次 - 1
  • 每轮的第二个ID(删除操作对应的折叠容器):2 * 当前循环轮次
    对应到Django模板语法,不需要引入自定义过滤器,用自带的add链式调用即可完成计算。

代码示例

优化写法(推荐)

为了避免重复计算、提升代码可读性,可以用{% with %}标签先缓存每轮计算出的两个数值,后续直接调用变量即可:

{% for comment in comments %}
{% with num1=forloop.counter|add:forloop.counter|add:"-1" num2=forloop.counter|add:forloop.counter %}
<!-- 三点操作按钮 -->
<button class="btn btn-outline-secondary" data-toggle="collapse" data-target=".multi-collapse"
        aria-expanded="false" 
        aria-controls="multiCollapseComment{{ num1 }} multiCollapseComment{{ num2 }}">
    <i class="fas fa-ellipsis-v"></i>
</button>
<!-- 折叠的操作按钮组 -->
<div class="row">
    <div class="col">
        <div class="collapse multi-collapse" id="multiCollapseComment{{ num1 }}">
            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="#">Edit</a>
        </div>
    </div>
    <div class="col">
        <div class="collapse multi-collapse" id="multiCollapseComment{{ num2 }}">
            <a class="btn btn-outline-danger btn-sm mt-1 mb-1" href="#">Delete</a>
        </div>
    </div>
</div>
{% endwith %}
{% endfor %}

效果验证

循环运行结果完全符合预期:

  • 第1次循环(forloop.counter=1):生成id为multiCollapseComment1、multiCollapseComment2
  • 第2次循环(forloop.counter=2):生成id为multiCollapseComment3、multiCollapseComment4
  • 第3次循环(forloop.counter=3):生成id为multiCollapseComment5、multiCollapseComment6
    完全不会出现之前的id重叠偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 22:24:00