liquid
liquid copied to clipboard
Add separator to For tag
This adds the ability to add a separator to be outputted between iterations of a for loop.
For example, to add commas between elements:
{% for item in items separator: ', ' %}{{ item }}{% endfor %}
Without this, you have to use a conditional to avoid outputting a separator after the last element:
{% for item in items %}{{ item }}{% unless forloop.last %}, {% endunless %}{% endfor %}
For such a trivial case shown above, the join filter could be used. However, the separator option is useful when there's more than just a simple output inside the loop:
{% for item in items separator: '<br>' %}
<b>{{ item.title | upcase }}</b>
{% endfor %}
Benchmarks on master:
[lax]
parse: 24.582 (± 0.0%) i/s - 1.476k
parse & run: 16.395 (± 0.0%) i/s - 984.000
[strict]
parse: 20.304 (± 0.0%) i/s - 1.218k
parse & run: 14.303 (± 0.0%) i/s - 858.000
Benchmark with the new separator:
[lax]
parse: 25.058 (± 0.0%) i/s - 1.504k
parse & run: 16.546 (± 0.0%) i/s - 993.000
[strict]
parse: 20.175 (± 0.0%) i/s - 1.210k
parse & run: 14.285 (± 0.0%) i/s - 857.000
@fw42 please review when you get a chance.
Isn't this the same as {{ items | join: ", " }}?
Sorry, I should read the whole description before answering :-)
I'm pretty indifferent about this... @pushrax @dylanahsmith?
@carolineschnapp you think this would be useful?
It could be useful yes :+1:
A did a Find in Files for {% unless forloop.last %} in our own themes and it's always the same scenarios that will be helped by this.
- A comma separated list of tags that are links:
{% for tag in article.tags %}
<a href="{{ blog.url }}/tagged/{{ tag | handle }}">{{ tag }}</a>{% unless forloop.last %}, {% endunless %}
{% endfor %}
-
Listing articles, comments, or search results, with a divider line between them (CSS could be used instead but it isn't):
{% unless forloop.last %} <hr class="divider" /> {% endunless %} -
Separator between links in link list:
{% for link in linklists.footer.links %}<a href="{{ link.url }}">{{ link.title | escape }}</a>{% unless forloop.last %} <span>|</span>
Indifferent as well, I don't mind this but I also think many cases should be accomplished with lists and CSS instead.
Code looks good in either case.
Thanks @pushrax. For what it's worth, I've been using this in production for a few years now, and it comes in handy pretty often and reduces the noise in otherwise trivial for loops.
@nickpearson: Can you rebase this?
@fw42 Sure thing — all done.
:+1: