Olivier Pons
Olivier Pons

Reputation: 15778

How to use the current index to get the value of another array?

I've read this, and I have an array like that:

context[u'erreurs'] = {
    'aa': {'titres': [], 'liste': [], 'urls': []},
    'bb': {'titres': [], 'liste': [], 'urls': []},
    '...': {'titres': [], 'liste': [], 'urls': []}
}

If there's an error, 'titres', 'liste' and 'urls' become array of strings, filled with adequates values.

In my template, if erreur is set I do this:

    {% for idx, tab in erreurs.items %}
        <ul>
        {% for e in tab.liste %}
            {% if user.is_authenticated %}
            <li><a href="{{ tab.urls[forloop.counter0] }}">{{ e }}</a></li>
            {% else %}
            <li>{{ e }}</li>
            {% endif %}
        {% endfor %}
        </ul>
    {% endfor %}

I would like to use the current index to use the value that is in another array, here: tab.urls. It doesn't work and gives me the error:

Could not parse the remainder: '[forloop.counter0]' from 'tab.urls[forloop.counter0]'

How to solve this?

Upvotes: 0

Views: 285

Answers (2)

Sayse
Sayse

Reputation: 43300

You need to make an actual model that represents the data then the task becomes trivial

class YourModel(object):
    titre = ''
    liste = '' 
    url = ''

context[u'erreurs'] = {
    'aa': [],  # List of model
}

{% for idx, tab in erreurs.items %}
    <ul>
    {% for model in tab %}
        {{ model.titre }}
        {{ model.liste }}
        {{ model.url }}
    {% endfor %}
    </ul>
{% endfor %}

Upvotes: 0

Alex Morozov
Alex Morozov

Reputation: 5993

Unfortunately, Django's templates don't support such syntax. You should put together a custom template filter:

# yourapp/templatetags/yourapp_tags.py:
from django import template
register = template.Library()

@register.filter
def at_index(array, index):
    return array[index]

and use it like:

{% load yourapp_tags %}
{{ tab.urls|at_index:forloop.counter0 }}

Upvotes: 1

Related Questions