how do I set a list item by index in jinja2
Asked Answered
T

2

11

hello I want to set the value of an item in a list in jinja2, for that I'm trying

<code>
{% set arr=[0,0,0,0,0,0,0,0] %}
{% print arr %}
{% set arr[1] = 1 %}
{% print arr %}
</code>

but receive an error message saying:

TemplateSyntaxError: expected token '=', got '['

please any advice, thanks in advance

Triacid answered 6/2, 2015 at 14:15 Comment(2)
Please man don't use Jinja2 for logic implementation. Dedicate views from the business logic. Do such job in your Python script and pass to Jinja2 data which is ready to display.Arcadia
Jinja intentionally makes it hard to modify data on the template side, because it's not the place you should modify data. You should treat the data as if it is immutable. You can create totally new values from parts of old values (with set) but you cannot mutate an old value so only part of it is new. And you should not want to. (You can do this by importing the do block extension to jinja, but again you really should not do it that way).Martlet
A
9

You can do it like this:

In [25]: q = '''{% set arr=[0,0,0,0,0,0,0,0] %}
{% print arr %}
{% if arr.insert(1,1) %}{% endif %}
{% print arr %}'''

In [26]: jinja2.Template(q).render()
Out[26]: u'\n[0, 0, 0, 0, 0, 0, 0, 0]\n\n[0, 1, 0, 0, 0, 0, 0, 0, 0]'

In [27]: 
Antioch answered 6/2, 2015 at 14:26 Comment(3)
Absolutely should not use side effects of things like list.insert or dict.update to accomplish these types of tasks.Martlet
thank you, it work. Thanks to all for recomendations about not using templates for this, I'm just debugging and this way is the fastest for me to do at this time, thanksTriacid
if this is the only way then what is the harm?Grotesquery
A
0

Like others have said, doing this in the template isn't considered a good practice. However, if you're like me and is writing complex templates with a bunch of logic in them, this is a one-liner:

    {% set zero_pos = 0 %}
    {% set values = [ 0x11, 0x22, 0x33, 0x44 ] %}
    {% set _ = values.__setitem__(zero_pos, 0) %}

Source

Antipyretic answered 9/5, 2024 at 19:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.