首页 > python > 打破或停止django中的forloop.counter

打破或停止django中的forloop.counter (Breaking or stopping a forloop.counter in django)

问题

forloop.counterfor循环中应用了一个用数字标记每个对象但是我希望它只对前五十(50)个对象进行编号而忽略其余对象。这是我的代码

{% load thumbnail %}

{% for image in most_viewed %}

<div class="image">
<a href="{{ image.get_absolute_url }}">
{% thumbnail image.image "200x200" crop="10%" as im %}
<span class="forloop">**{{ forloop.counter }}**</span>
<a href="{{ image.get_absolute_url }}"> <img src="{{ im.url }}">  </a> 

{% endthumbnail %}

</div>
{% endfor %}

基本上,对象51及以上应该没有数字

解决方法

您可以尝试使用切片重写for循环

{% for image in most_viewed|slice:":50" %}

它将在most_viewed中对前50个图像进行迭代

编辑 - 刚看到你的编辑。您可以尝试使用条件语句forloop.counter <= 50

{% for image in most_viewed %}

  <div class="image">
    ...
    {% if forloop.counter <= 50 %}
      <span class="forloop">**{{ forloop.counter }}**</span>
    {% endif %}
    ...
  </div>

{% endfor %}

问题

I applied a forloop.counter to label each object numerically in a for loop But I want it to number only the first fifty(50) objects and ignore the rest. Here is my code

{% load thumbnail %}

{% for image in most_viewed %}

<div class="image">
<a href="{{ image.get_absolute_url }}">
{% thumbnail image.image "200x200" crop="10%" as im %}
<span class="forloop">**{{ forloop.counter }}**</span>
<a href="{{ image.get_absolute_url }}"> <img src="{{ im.url }}">  </a> 

{% endthumbnail %}

</div>
{% endfor %}

Basically, objects 51 and above should be without numbers

解决方法

You can try using slice to rewrite the for loop as

{% for image in most_viewed|slice:":50" %}

It will do the iteration for first 50 image in most_viewed.

Edit - Just saw your edit. You can try using the conditional statement forloop.counter <= 50

{% for image in most_viewed %}

  <div class="image">
    ...
    {% if forloop.counter <= 50 %}
      <span class="forloop">**{{ forloop.counter }}**</span>
    {% endif %}
    ...
  </div>

{% endfor %}
相似信息