8

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 %}

3 Answers 3

15

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

4
  • Awesome, I could not find this anywhere in the Craft docs, thank you! Oct 3, 2014 at 16:31
  • 3
    You didn't find it in the Craft docs because it's a native Twig variable.
    – Lindsey D
    Oct 3, 2014 at 17:10
  • 2
    Is there an advantage to this vs wrapping the "," in a {% if not loop.last %}? Oct 4, 2014 at 3:57
  • Personal preference.
    – jnowland
    Oct 4, 2014 at 4:12
17

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 %}
3
  • 8
    To clean it up even further: {{ not loop.last ? "," }}
    – Lindsey D
    Oct 4, 2014 at 5:18
  • @LindseyD Your suggestion seems very neat but why do I get unexpected char '?' ?
    – Pranasas
    Nov 7, 2017 at 9:30
  • @Pranasas I don’t know. I suggest starting a new thread, since this one is over 3 years old. Feel free to link back to this thread (or answer) for reference.
    – Lindsey D
    Nov 7, 2017 at 14:16
5
{% for category in entry.mediaType %}
    <b>{{ category.title }}</b>{{ "," if not loop.last }}
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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