[Django]-Django {% if forloop.first %} question

28👍

Edited:

I have never used these variables but I think forloop.parentloop.first should do it. If not blame me to have misunderstand the Django docs. 😉

You should check if you are within the parentloop and and then within the first nested node. Please try this modified template. It should you give the right direction.

{% if forloop.parentloop.first %}     
   I am in the first loop of the parent
{% else %}
{% if forloop.first %}  
    <div class='side_header' id='dark_gamelink_side'>
        <a class='actionheader' href=""></a>
    </div>
{% endif %}
{% endif %}
👤jazz

1👍

I think the best way to solve this isn’t to detect if this is the first iteration in the loop, but rather to write your HTML so that is outside the loop entirely.

You should only be writing HTML elements in the for loop that you actually want repeated for each iteration. If that doesn’t work, rethink how you’re providing the data to your view (object_list, game, category, etc) so that you can write your markup more easily.

The beginning of your view will probably look something like this:

<div class='side_header' id='dark_gamelink_side'>
    <a class='actionheader' href=""></a>
</div>
{% for object in object_list %}
{% with game=object.game %}
{% for category in object.game.objectmeta.categories.all %}
{% if category.name|title == 'Puzzle' %}

Leave a comment