shrewdbeans
shrewdbeans

Reputation: 12549

Python / Django - have a certain number of items in a loop wrapped in a div

I have a simple for loop in Django, outputting a series of teaser stories. Each is wrapped in a div with a class of row. I have an varibale called num_of_rows, that adds a class of hidden after 2 loops, which hides these divs from view with css.

Here's my code:

{% block content %}
<h1>{{ section.title }}</h1>

{% for story in story_list %}
<div class="row {% if num_of_rows > 2 %} hidden{% endif %}">
    <h2>
      <a href="{{ story.get_absolute_url }}">
        {{ story.headline|upper }}
      </a>
    </h2>
    <p>{{ story.tease|truncatewords:"100" }}</p>
</div>
{% endfor %}
{% endblock %}

What I'd like to do is, instead of adding a class of hidden to each individual row, wrap all of the items after 2 items in a separate div and then hide with CSS from that, using Django. This way I can create a much smoother slide-down effect with jQuery.

Upvotes: 1

Views: 389

Answers (1)

jterrace
jterrace

Reputation: 67113

You can use the forloop variables for this:

{% for story in story_list %}
  {% if forloop.counter == 3 %}<div class="hidden">{% endif %}
  <div class="row">
      <h2>
        <a href="{{ story.get_absolute_url }}">
          {{ story.headline|upper }}
        </a>
      </h2>
      <p>{{ story.tease|truncatewords:"100" }}</p>
  </div>
  {% if forloop.counter > 2 and forloop.last %}</div>{% endif %}
{% endfor %}

Upvotes: 1

Related Questions