0

Possible Duplicate:
Get list item dynamically in django templates

How to get list items with variable counter. The aim is to get the so item instead of list

not like this

{% for item in listModels %} 
 {{ item | safe }} 

{% endfor %}

so work

{% for i in listModels|length|get_range %} // get size list 

 {{ listModels.i | safe }}

{% endfor %}

do not work

{% for i in listModels|length|get_range %} // get size list 

 {{ listModels.i | safe }}

{% endfor %}
Community
  • 1
  • 1
Krasimir
  • 1,806
  • 2
  • 18
  • 31

3 Answers3

1

Django templates will not allow you to do this. I'm not going to lecture you on keeping your logic out of your templates, because I think it's a stylistic choice. But understand that this is the easiest way. If you need to use the index, you can access it as a forloop property, as explained in the documentation.

If you really want variable indexing, you could make your own custom template tag to do it. But, in this case, I suggest you use a more powerful templating language, like Jinja2, instead of torturing the Django templating language.

acjay
  • 34,571
  • 6
  • 57
  • 100
  • The question is, should warped list with two first round the two list are the same number of elements – Krasimir Jan 09 '13 at 19:05
  • I'm not sure I understand what you're asking, but if you're saying you have two lists you want to iterate over in tandem, then I suggest using ``zip`` to merge them into one list of tuples. – acjay Jan 09 '13 at 19:40
  • 1
    It's a built-in function, useful when you want to iterate over multiple matched lists with one loop: http://docs.python.org/2/library/functions.html#zip – acjay Jan 09 '13 at 20:33
0

Django Template Language provides you a way to do this...

{% for item in listModels %} 
 {{ forloop.counter }} 

{% endfor %}
Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
0

I fixed like I did the following:

{{ listModelsData|lookup:i|lookAttribute:"author" }} -// this equal listModelsData[i].author - this code in python 

@register.filter
def lookAttribute (d, token):
     return getattr (d, token)
Krasimir
  • 1,806
  • 2
  • 18
  • 31