Search code examples
python-3.xjinja2

Jinja2 prints none when appending to a loop


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]


Solution

  • 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.

    Edit: @New Coder asked if there was a less hacky way to do it, and there is! Use _ as a throwaway variable to store the None output, like so: {% set _ = keyword_list.append(keyword['keywords_id']) %}