0

I am passing list called 'list' to view and i want to create links with href attribute as value of list element iterated by forloop.counter0.

As far as I know getting list element requires such code :

{{ list.0 }}

But how can I iterate with forloop.counter0 values?

What I do is something like this :

{% for name in names %}
    <tr>
         <a href="/foo/bar/{{ list.forloop.counter0 }}">
            {{ name }}
         </a>
    </tr>
{% endfor %}

But that doesnt apply any value and I tried with some more bracketting, but no succes.

How can I do it?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
  • 1
    Possible duplicate of [Get list item dynamically in django templates](http://stackoverflow.com/questions/8948430/get-list-item-dynamically-in-django-templates) – LostMyGlasses Feb 15 '16 at 17:37

1 Answers1

0

Edit: OK, thanks for the clarification. I'd suggest a custom templatetag.

Create a yourapp/templatetags/ dir. In that, create a blank file named __init__.py (this is required for Django to acknowledge the folder) and a file called custom_tags.py.

In custom_tags.py create a tag like so:

from django import template

register = template.Library()

@register.filter('list_index')
def list_index(mylist,index): 
    return mylist[index]

Not in your template, add to the top:

{% load custom_tags %}

to import/initialize the library.

Now you can use this tag like so:

<a href="/foo/bar/{% list_index list forloop.counter0 %}">

to retrieve the item from your list at index provided by forloop.counter0.

Quick note - list is in the Python standard library, so never use it as a variable name (just in case this is mirroring your code).

Ian Price
  • 7,416
  • 2
  • 23
  • 34