我想运行for循环来显示所有图像,但问题是我必须更改每个图像的"id“(pic-1 -> pic-2 ...so on)我知道如何在普通Python中做到这一点,但我在Django的模板中却迷路了。
<div class="preview-pic tab-content">
<div class="tab-pane active" id="pic-1"><img src="{{product.image.url}}"></div>
{% for image in image_list %}
<div class="tab-pane" id="pic-2"><img src="http://placekitten.com/400/252" /></div>
<div class="tab-pane" id="pic-3"><img src="http://placekitten.com/400/252" /></div>
<div class="tab-pane" id="pic-4"><img src="http://placekitten.com/400/252" /></div>
<div class="tab-pane" id="pic-5"><img src="http://placekitten.com/400/252" /></div>
{% endfor %}
</div>
<ul class="preview-thumbnail nav nav-tabs">
<li class="active"><a data-target="#pic-1" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li>
{% for image in image_list %}
<li><a data-target="#pic-2" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li>
<li><a data-target="#pic-3" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li>
<li><a data-target="#pic-4" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li>
<li><a data-target="#pic-5" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li>
{% endfor %}
</ul>
</div>发布于 2019-08-19 23:50:55
您可以使用{{ forloop.counter }}或{{ forloop.counter0 }}
{% for image in image_list %}
<div class="tab-pane" id="pic-{{ forloop.counter }}"><img src="http://placekitten.com/400/252" /></div>
{% endfor %}请注意,
{{ forloop.counter }}起始索引%1
{{ forloop.counter0 }}起始索引%0
发布于 2019-08-19 23:50:23
您可以使用forloop.counter来获取循环索引:
{% for image in image_list %}
<div class="tab-pane" id="pic-{{ forloop.counter }}"><img src={{ image.url }} />
{% endfor %}如果你的pic计数器从2开始,你可以使用add模板标签:
{% for image in image_list %}
<div class="tab-pane" id="pic-={{ forloop.counter|add:1 }}"><img src={{ image.url }} />
{% endfor %}发布于 2019-08-20 00:21:56
您可以使用{{forloop.counter}}变量。这将返回循环的索引。
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop surrounding the current one有关内置模板、标签和过滤器的更多信息,请访问:https://docs.djangoproject.com/en/2.2/ref/templates/builtins/
https://stackoverflow.com/questions/57560072
复制相似问题