Search code examples
jinja2

Print comma separated values from list in same <p> in Jinja2


I want to print values from a list comma seperated in same p tag. I have tried something like this

{% for item in list %}
    <p>{{item}}{% if not loop.last %},{% endif %}</p>
{% endfor %}

But this print values on different lines
item1,
item2

I want everything to be printed in one line i.e item1, item2
I guess because p tag is within for loop so each time new p tag gets generated. Is there a way to read through list and not generate different p tag and print items in same p tag ?


Solution

  • Place the <p> tags outside the for loop. You can also use <span> to inline the items:

    <p>
    {% for item in list %}
    <span>{{item}}{% if not loop.last %},{% endif %}</span>
    {% endfor %}
    </p>