Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

I want to create a comma separated list of categories to which an entry belongs, but without the trailing slash on the last element... can't work out how to remove it!

{% for category in entry.mediaType %}
    <b>{{ category.title }}</b>,
{% endfor %}
share|improve this question

2 Answers 2

up vote 3 down vote accepted

There is a special tag inside for loops you can use for this

{% for category in entry.mediaType %}
    <b>{{ category.title }}</b>,
    {% if loop.last %}
        <b>{{ category.title }}</b>
    {% endif %}
{% endfor %}

Full list here

share|improve this answer
    
Awesome, I could not find this anywhere in the Craft docs, thank you! –  Matt Wilcox 13 hours ago
3  
You didn't find it in the Craft docs because it's a native Twig variable. –  Lindsey D 13 hours ago
1  
Is there an advantage to this vs wrapping the "," in a {% if not loop.last %}? –  Dustin Walker 2 hours ago
    
Personal preference. –  jnowland 2 hours ago

While your conditional is complete personally preference I would do the following as I find it slightly easier to read. Note the use of the {%- if -%} to trim whitespace:

{% for category in entry.mediaType %}
    <b>{{ category.title }}</b>
    {%- if not loop.last -%}
      ,
    {% endif %}
{% endfor %}
share|improve this answer
    
To clean it up even further: {{ not loop.last ? "," }} –  Lindsey D 57 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.