首页 > 解决方案 > How to insert an element into list at index in jinja2

问题描述

i have set the list of split string in a variable as:

test = a new version of app

{% set new_index = test.split(' ') %}

I am trying to insert 'easy' after 'new' so tried as:

{% set new_index = test.split(' ').insert(2,' easy') %}

then {{ new_index }} which returned None

also tried with a new variable as:

{% set test1 = new_index.insert(2,' easy') %}

this also returned the same None

I read docs in which insert method is never used in examples too

Is there a way to achieve this, any help is appreciated TIA

标签: flaskjinja2

解决方案


test = "a new version of app"
new_index = test.split(' ').insert(2,'easy')
print(new_index)

output

None

try This

test = "a new version of app"
new_index = test.split(' ')
new_index.insert(2,'easy')
print(new_index)

output

['a', 'new', 'easy', 'version', 'of', 'app']

Then Try this code for your jinja2 code

{% set new_index = test.split(' ') %}
{% set another_new_index = new_index.insert(2,' easy') %}

then {{ new_index }} would return the required output


推荐阅读