0

I define an argument which is of string type.

% set my_argument = 'list_from_gae' %}

I would like to pass this as an argument in a for loop:

{% for i in my_argument %}

do sth

{% endfor %}

The string literal of my_argument corresponds to a list passed from a python application. The code above doesn't work, but it does work if i replace my_argument in the for loop with the string literal.

{% for i in list_from_gae %}

do sth

{% endfor %}

How do you make jinja understand that my_argument is a variable and not a string literal?

LLaP
  • 2,528
  • 4
  • 22
  • 34

1 Answers1

1

You can't, not without additional work to get the context as a dictionary. See How to get a list of current variables from Jinja 2 template? Once you have that context you could do context()[my_argument].

You'd be better of putting list_from_gae in a dictionary passed to your template; you can then use that to access that name.

E.g. if you are now passing in:

template_values = {'list_from_gae': list_from_gae}

then instead pass in:

template_values = {'lists': {'list_from_gae': list_from_gae}}

and address these with:

{% for i in lists[my_argument] %}
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I do pass my list through `template_values = {'list_from_gae': list_from_gae}` from Google App Engine. Is that a dictionary you refer to? – LLaP Aug 16 '14 at 12:33
  • @LLaP: not really; you'd have to add *another* dictionary: `template_values = {'lists': {'list_from_gae': list_from_gae}}`, then use `lists[my_argument]`. – Martijn Pieters Aug 16 '14 at 12:35
  • Great, works fine. I would suggest you edit your answer - remove the first suggestion, just focus on the second one, and add the code example from your second comments. I'm gonna vote it up anyway, but it can be quite useful for other people to have everything in the answer. – LLaP Aug 16 '14 at 12:43
  • @LLaP: Well, it answers your original question; this is a normal pattern in answering; address both the original query and offer alternatives. – Martijn Pieters Aug 16 '14 at 12:44