7

I would like to output a tag-list like this:

foo, bar and baz

I know how to elegantly output a tag list with no comma after the last tag:

{% for tag in tags %}
    {{ tag }}{{ not loop.last ? ', ' }}
{% endfor %}

Is there a similarly elegant solution for getting the tags to display the way I want?

3 Answers 3

4

Bit of an old question, but here's a (subjectively) more elegant solution than the accepted answer using loop.revindex0:

{% for tag in tags %}
    {{ tag.type }}{{ loop.revindex0 == 1 ? ' and' : loop.revindex0 ? ', '  }}
{% endfor %}
1
  • Might be that revindex0 didn't exist yet at the time I originally posted my question :)
    – Florian
    Jan 7, 2019 at 11:09
6

Not very elegant, but... :)

{% for tag in tags %}
    {{ tag.type }}{{ loop.index < loop.length-1 ? ', ' : loop.index < loop.length ? ' and' }}
{% endfor %}
2
  • Elegant enough for me! I didn't know I could nest another ternary operation inside the first one. Thank you.
    – Florian
    Sep 5, 2014 at 8:55
  • 1
    You could use loop.revindex or loop.revindex0 to test how far you are from the end if you wanted to, for just a bit more elegance/obscurity. Jul 9, 2015 at 16:13
1

You can output tags as a list (using <li> and <ul> tags) and add commas and and with CSS:

li {display:inline}
li:before {content:', ';}
li:first-child:before {content:'';}
li:last-child:before {content:' and ';}

This will require that all the spaces between tags be removed so that your template code would look like this:

{% for tag in tags %}{{ tag }}{% 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.