Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Twig macro for converting list to sentence-like string (e.g. ["apples", "bananas, "carrots] becomes "apples, bananas, and carrots")
{# Loop through all items in a list, comma-separate them, but use "and" before the last item
e.g. ["apples", "bananas, "carrots] becomes "apples, bananas, and carrots" #}
{% macro to_sentence(items) %}
{% for item in items %}
{# First item #}
{% if loop.first %}
<span>{{ item }}{% if items|length > 2 %},{% endif %}</span>
{% else %}
{# Middle items #}
{% if not loop.first and not loop.last %}
<span>{{ item }}, </span>
{% endif %}
{# Last item #}
{% if loop.last %}
<span> and {{ item }}</span>
{% endif %}
{% endif %}
{% endfor %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.