1

Can I do something like this in the django templates ?:

firstList = ["foo", "bar"]
secondList = ["foo", "bar"]
for counter_one, _firstList in enumerate(firstList):
  for counter_two, _secondList in enumerate(secondList):
    if firstList[counter_one] == secondList[counter_two]:
      print(firstList[counter_one])

Because if I could that would be super awesome :D

2
  • Why don't you use _firstList instead of firstList[counter_one] (same for _secondList, secondList[counter_two]) ? Commented Dec 20, 2013 at 11:41
  • It's more for myself because I am used to for loops since yesterday ^^ I didn't want to confuse things Commented Dec 20, 2013 at 11:52

2 Answers 2

1
>>> from django.template import Template, Context
>>> t = Template('''
...     {% for first in firstList %}
...         {% for second in firstList %}
...             {% if first == second %}
...                 {{ first }}
...             {% endif %}
...         {% endfor %}
...     {% endfor %}
... ''')
>>> t.render(Context({'firstList': ['foo', 'bar'], 'secondList': ['foo', 'bar']}))
u'\n    \n        \n            \n                foo\n            \n        \n            \n        \n    \n        \n            \n        \n            \n                bar\n            \n        \n    \n'
>>> print(t.render(Context({'firstList': ['foo', 'bar'], 'secondList': ['foo', 'bar']})))


                foo



                bar

Use fooloop.counter0 or forloop.counter if you need an index of inner loop. (0-based, 1-based). See for template tag.

BTW, the code does not need index because the code only print elemetn of the list.

Sign up to request clarification or add additional context in comments.

Comments

0

You might want to take a look at Custom template tags and filters

Link to official documentation

Also Django Book also provides a tutorial for Advanced Templating.

Link to Django Book - Advanced Templates

Its very easy to create your own template filters. I hope this helps

1 Comment

I will have a look at it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.