LLaP
LLaP

Reputation: 2727

Can jinja variable be passed as an argument in for loop?

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?

Upvotes: 0

Views: 1543

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

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] %}

Upvotes: 1

Related Questions