5

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?

1
  • 1
    Why do you want to do this? Aug 16 '15 at 3:13
7

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 }}
3
  • 4
    and how / where do we do this? "Be sure to add operator to globals"
    – Jessi
    Mar 6 '19 at 17:51
  • 1
    Wherever you set up your jinja environment.
    – t-8ch
    Mar 9 '19 at 20:38
  • Why have flow controls, conditional logic, operators at all then? Helm, Ansible, SaltStack all implement logic. Do handle logic in templates. Carefully. Aug 26 '21 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.