Created
February 18, 2020 19:32
-
-
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")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# 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