0

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?

Community
  • 1
  • 1
Olivier Pons
  • 15,363
  • 26
  • 117
  • 213

2 Answers2

1

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 }}
Alex Morozov
  • 5,823
  • 24
  • 28
0

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 %}
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • Thank you for your answer,but `titre`, `liste` and `url` are arrays so I cant handle them like this. – Olivier Pons Jan 09 '16 at 21:02
  • @OlivierPons - sure you can, its just a pre-processing step to convert the three arrays into one object array before assigning to the context – Sayse Jan 09 '16 at 22:01