Gonzalo Murillo
Gonzalo Murillo

Reputation: 91

Can a Jinja template variable be accessed by index position, if the index position value is defined within a variable?

I am using Flask to build a Web APP that is going to display the average values of several columns for a list of persons.

Let´s say I have 4 fields (field1,field2,field3,field4) and several rows of information for those 4 fields for every person on a list of persons.

I calculate the averages for each field and for each person and store them in a variable called averages, which is a list of lists. Each item of the variable averages is a list that contains the average for each field for one specific person

So, for example:

averages = [[5,6,5,4],[2,3,4,5]]

Contains the average of field1,field2,field3,field4 for two persons, each person represented by a list within the list of lists which is averages.

I hope it is clear so far...

Now the Flask part.

When I render the template, I pass averages as variable:

return(render_template("display_averages.html",averages=averages))

From the "Template Designer Documentation" of Jinja

You can use a dot (.) to access attributes of a variable in addition to the standard Python getitem “subscript” syntax ([]).

So I can do, this: {{ averages.0.1 }}, and based on the example below where the variable averages contains the following values:averages = [[5,6,5,4],[2,3,4,5]]

{{ averages.0.1 }} will be substituted by 6 as it is the element 1 in the list 0

So far so good, but what I want to achieve is to have a counter in the template: {% set person_counter = 0 %} and use that person_counter to access the items in the averages variable.

So what I would have done to achieve it, would have been:

{{ averages.person_counter.0 }}

But it does not work, it does return error:

jinja2.exceptions.TemplateSyntaxError: expected name or number

I know that I can do:

{% for average in averages %}
{{average}}
{% endfor %}

To iterate over the elements of the list averages, but that is not what I want to achieve.

My specific question is

Can I somehow use a Jinja variable as an index variable for accessing another Jinja variable which is a list?

I think the issue is well explained.

What other options do I have for achieving something like what I have asked?

Upvotes: 1

Views: 1546

Answers (1)

Karl Moodh
Karl Moodh

Reputation: 2711

averages.0.1 is the same as averages[0].1 (or even averages[0][1]), however the second version also supports variables.

In your case the following should work:

{{ averages[person_counter].1 }}

http://jinja.pocoo.org/docs/dev/templates/#variables

Upvotes: 2

Related Questions