[Django]-Django Template System: How do I solve this looping / grouping / counting?

4👍

Following Jeb’s suggeston in a comment, I created a custom template tag.

I replaced {{ forloop.counter }} with {% counter %}, a tag that simply prints how many times it’s been called.

Here’s the code for my counter tag.

class CounterNode(template.Node):

  def __init__(self):
    self.count = 0

  def render(self, context):
    self.count += 1
    return self.count

@register.tag
def counter(parser, token):
  return CounterNode()

1👍

This isn’t exactly neat, but may be appropriate for someone:

{% for article in articles %}        
   {% ifchanged article.section %}
      {% if not forloop.first %}</ul>{% endif %}
      <h4>{{article.section}}</h4>
      <ul>
   {% endifchanged %}
          <li>{{forloop.counter}}. {{ article.headline }}</li>
   {% if forloop.last %}</ul>{% endif %}
{% endfor %}
👤Tom

-1👍

I think you can use forloop.parentloop.counter inside of the inner loop to achieve the numbering you’re after.

👤Jeb

-1👍

You could just use an ordered list instead of unordered:

{% regroup articles by section as articles_by_section %}

<ol>
{% for article in articles_by_section %}        
    <h4>{{ article.grouper }}</h4>
    {% for item in article.list %}  
        <li>{{ item.headline }}</li>
    {% endfor %}
{% endfor %}
</ol>

Leave a comment