5

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

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

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

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 %}
  • 8
    To clean it up even further: {{ not loop.last ? "," }} – Lindsey D Oct 4 '14 at 5:18
  • @LindseyD Your suggestion seems very neat but why do I get unexpected char '?' ? – Pranasas Nov 7 '17 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 '17 at 14:16
3
{% 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, privacy policy and cookie policy

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