Search code examples
pythonjinja2

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


Solution

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