How to remove unwanted commas using Jinja2

Viewed 590

How do I make this...

, ,apple,orange, , , ,mango, , 

into...

apple,orange,mango

using Jinja2?

I have tried this...

{% set fruits = ', ,apple,orange, , , ,mango, , ' %}

{% set fruits_array = fruits.split(',') %}

{% for fruit in fruits_array %}
  {%- if fruit|trim != '' -%}
    {{- fruit|trim -}}
    {{ "," if not loop.last }}
  {%- endif -%}
{% endfor %}

there is always a trailing comma in the result.

1 Answers

I manage to solve this using this...

{% for fruit in fruits_array if fruit|trim != '' %}
  {{- fruit|trim -}}
  {{ "," if not loop.last }}
{% endfor %}
Related