Home > Enterprise >  forloop.counter for two dimensional array in Django Template
forloop.counter for two dimensional array in Django Template

Time:07-06

I'm using forloop.counter for my list. I have two-dimensional list. If I try this, all works perfect.

{{team_members|index:1|index:0}}

But when I try this:

{{team_members|index:forloop.counter|index:0}}

where forloop.counter = 1 it wrotes me

list index out of range

Can you please explain why? If I code like this:

{{team_members|index:forloop.counter}}

it works perfect too.

Edit

<div  data-toggle="tooltip" data-placement="bottom" data-html="true" twipsy-content-set="true"  title="Leader: 
                {% with team_member=team_members|index:forloop.counter %}
                    {{ team_member|index:0 }}
                {% endwith %}<br>Members: {{team_members.1.1}}">
                {{team.name|teamName}}
</div>

CodePudding user response:

If you chain the things like that the template engine will try to applu the index template filter on forloop.counter not on team_members[forloop.counter].

The only way to control the order of evaluation is to use the {% with %} template tag:

{% with team_member=team_members|index:forloop.counter %}
    {{ team_member|index:0 }}
    {# or with the dot syntax: #}
    {{ team_member.0 }}
{% endwith %}
  • Related