Home > Net >  Jinja2 prints none when appending to a loop
Jinja2 prints none when appending to a loop

Time:04-13

In my flask application I am creating a list and appending. When I append to the list None prints.

{% set keyword_list = [] %}
{% for keyword in keywords_data %}
    {{ keyword_list.append(keyword['keywords_id']) }} //None prints for each iteration
{% endfor %}

{{ keyword_list | join(',') }} prints 1,2,3 {{ keyword_list }} prints [1,2,3]

CodePudding user response:

Change it to {{ keyword_list.append(keyword['keywords_id']) or "" }}, which uses the feature of ors that returns the first truthy answer. Since strings are always truthy in Jinja, and None is falsy, it returns the empty string, outputting nothing to the end-user.

  • Related