Comma list Liquid snippet for Shopify

I’m trying to get back into the habit of getting regular content up on here, so I’m going to make an effort to extract bits and pieces from the various Shopify projects we’re working on over at Disco that could be useful for folks.

This one’s a simple Liquid snippet for outputting comma-formatted lists (eg “Monday, Tuesday and Wednesday” given a list of items:

{%- comment -%}

  snippets/comma-list.liquid

  A simple Liquid snippet for outputting a comma-separated text list, with
  options for Oxford comma control.

  See https://gavinballard.com/comma-list-liquid-snippet-for-shopify

{%- endcomment -%}
{%- assign second_last_index = items.size | minus: 1 -%}
{%- for item in items -%}
  {%- assign comma_list_append = ', ' -%}
  {%- if forloop.index == second_last_index -%}
    {%- if no_oxford_comma or items.size == 2 -%}
      {%- assign comma_list_append = ' and ' -%}
    {%- else -%}
      {%- assign comma_list_append = ', and ' -%}
    {%- endif -%}
  {%- endif -%}
  {%- if forloop.last -%}
    {%- assign comma_list_append = '' -%}
  {%- endif -%}
  {%- assign comma_list_output = comma_list_output | append: item | append: comma_list_append -%}
{%- endfor -%}
{{- comma_list_output -}}

Use it like this:

{% assign days_of_the_week = 'Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday' | split: ',' %}
The days of the week are {% include 'comma-list', items: days_of_the_week, no_oxford_comma: true %}.

outputs:

The days of the week are Monday, Tuesday, Wednesdsay, Thursday, Friday, Saturday and Sunday.