0

Assume that nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this case, {{ nested_list.0.1 }} would print 2 in template


Q. How can I access to nested list by variable in template ?

For example, {{ nested_list.{{ some_variable }}.1 }}. Where some variable contains the index that I wish to retrieve (0 in the first example). Of course, it yields TemplateSyntaxError.

Sayse
  • 42,633
  • 14
  • 77
  • 146
Chemical Programmer
  • 4,352
  • 4
  • 37
  • 51
  • You are talking about nesting of template variables. This might help you: http://stackoverflow.com/questions/26391133/how-to-handle-nested-template-variables – Aswin Murugesh Jul 24 '15 at 05:20
  • Thanks for your help. However, that solution didn't solved my problem. I've tried `{{ nested_list.add:some_variable }}` which yields nothing. – Chemical Programmer Jul 24 '15 at 05:34
  • hmm, maybe consider using dict? See here http://stackoverflow.com/a/1724201/953553 – andilabs Jul 24 '15 at 06:07
  • 1
    you might want to implement a custom [`template filter`](https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/) – Ozgur Vatansever Jul 24 '15 at 06:12
  • @ErnestTen Thanks. Your answer helped me a lot. So the conclusion is that it is impossible from template side. I'd preprocess using `zip` function in controller. – Chemical Programmer Jul 24 '15 at 06:23
  • I've added an extra sentence to better explain what (I think) you are trying to do, please revert and explain if this is incorrect – Sayse Jul 24 '15 at 06:24
  • Even though I use `template filter`, I should use variable in another variable. So it could not solve the problem. – Chemical Programmer Jul 24 '15 at 06:26
  • 1
    Also, potentially off topic but it slightly looks as though you are trying to do logic in the template. It may be preferred to do this preprocessing in the view – Sayse Jul 24 '15 at 06:26
  • 1
    @Sayse Yes, I agree with you. Thanks for your recommendation. – Chemical Programmer Jul 24 '15 at 06:28

0 Answers0