Horai Nuri
Horai Nuri

Reputation: 5578

Is it possible to show multiple times the same queryset on template?

This is an odd question but I'd like to be able to show the same queryset multiple times on my template using different {% for loops %}, I'm trying to avoid copy pasting each {% for loops %}.

Let's say I have my views.py like this :

...
    chicken = Chicken.objects.filter(id=1)
    return render(request, 'chicken.html', {'chicken':chicken}

chicken.html : the example below is the one I'm avoiding.

<!-- {{ egg }} has the same value everywhere --> 

{% for egg in chicken %} <!-- has a different index than other loops -->
    <p id="egg_1">{{egg}}</p> 
{% endfor %}

{% for egg in chicken %}
    <p id="egg_2">{{egg}}</p>
{% endfor %}

{% for egg in chicken %}
    <p id="egg_3">{{egg}}</p>
{% endfor %}

...x52...

Is there a way to automatise this while having a different index on each loop ?

I'm searching for something like this :

{% for chicken x52 %}
    {% for egg in chicken %}
        <p id="egg_index">{{egg}}</p> <!-- each with different index -->
    {% endfor %}
{% endfor %}

Upvotes: 0

Views: 149

Answers (1)

Alasdair
Alasdair

Reputation: 309099

For the example you have given, you could add a variable loops to the context:

chicken = Chicken.objects.filter(id=1)
loops = range(1, 53)
return render(request, 'chicken.html', {'chicken':chicken, 'loops': loops}

Then loop through loops in the template:

{% for loop in loops %}
  {% for egg in chicken %} <!-- has a different index than other loops -->
    <p id="egg_{{ loop }}">{{egg}}</p> 
  {% endfor %}
{% endfor %}

If you don't want to add a variable to the context, there are some different approaches suggested on this question, some hackier than others.

Upvotes: 2

Related Questions