mauricio
mauricio

Reputation: 113

how do I set a list item by index in jinja2

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

Upvotes: 11

Views: 27927

Answers (2)

Leonardo
Leonardo

Reputation: 1891

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

Upvotes: 0

Vor
Vor

Reputation: 35139

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]: 

Upvotes: 9

Related Questions