jas
jas

Reputation: 1582

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 ?

Upvotes: 2

Views: 2725

Answers (3)

cevaris
cevaris

Reputation: 5794

This provided me with the correct, expected spacing while allowing for looping over models, not just scalar types

{% for item in list %}
    {{ item + ',' if not loop.last else item}}
{% endfor %}

And if item was an model, i.e. object, with some text field "name"....

{% for item in list %}
    {{ item.name + ',' if not loop.last else item.name}}
{% endfor %}

Upvotes: 0

SumanKalyan
SumanKalyan

Reputation: 1761

If you want to print a list with comma separated, just use join in jinja.

<p>{{ list | join(", ") }}</p>

Upvotes: 3

jrbedard
jrbedard

Reputation: 3730

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>

Upvotes: 3

Related Questions