Skip to content

Instantly share code, notes, and snippets.

@jonnymaceachern
Created February 18, 2020 19:32
Show Gist options
  • Save jonnymaceachern/931fc5fa020e5c5636a11fb0ce36a60b to your computer and use it in GitHub Desktop.
Save jonnymaceachern/931fc5fa020e5c5636a11fb0ce36a60b to your computer and use it in GitHub Desktop.
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