Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working with arrays in jinja2

I'm passing an array object from a view in my Flask server to the jinja2 template. Let's say the name is aList. When I try to change a value inside of aList like this:

in Flask:

aList = ['a', 'b', 'c']

in the template:

{% set aList[0] = "work, dammit!" %}

I get this error that tells me that "=" is expected instead of "[" in the template.

Can someone tell what the right way of working with arrays is in jinja2?

like image 892
Денис Балобин Avatar asked Aug 15 '15 23:08

Денис Балобин


1 Answers

First: Logic should not be handled in the template!

Second: If you really have to:

If jinja does not accept the array syntax you should be able to work around it by using operator.setitem from the stdlib. (Be sure to add operator to globals)

{% set foo = [0, 1, 2, 3, 4] %}
{% set _ = operator.setitem(foo, 'some stuff') %}
{{ foo }}
like image 130
t-8ch Avatar answered Oct 04 '22 06:10

t-8ch