2

I need to be able take a list of objects in liquid and display them on the page in a specific format.

If I have an array of objects (pages), I need to be able to print them in the following way:

list category names (page.category.name)

list each subcategory name with a list of pages under each subcategory name (page.subcategory.name and page.title)

Typically in ruby I would simply group the pages but I can't do that in liquid. The other thing I tried was to capture unique lists of categories and subcategories for pages but I couldn't find a way to get a unique list of items from an array. Any suggest help would be great.

miskander
  • 125
  • 8

1 Answers1

6

I'm a little late to answer your question, but maybe this will help someone else struggling with the same problem. It's a bit hacky, as Liquid logic tends to be, but it works (at least for me, on Shopify).

Assuming you have a 'pages' array that looks like this:

pages = [
    { name: 'Page 1', category: { name: 'pants'  } },
    { name: 'Page 2', category: { name: 'pants'  } },
    { name: 'Page 3', category: { name: 'shoes'  } },
    { name: 'Page 4', category: { name: 'shirts' } },
    { name: 'Page 5', category: { name: 'shoes'  } }
]

This code will return only unique category names:

{% assign delimiter = "," %}
{% assign names_str = "" %}
{% assign names = pages | map: 'category' | map: 'name' %}

{% for name in names %}
    {% assign names_arr = names_str | split: delimiter %}
    {% unless names_arr contains name %}
        {% assign names_str = names_str | append: delimiter | append: name %}
    {% endunless %}
{% endfor %}
{% assign names_uniq = names_str | remove_first: delimiter | split: delimiter %}

Result:

names_uniq => [ 'pants', 'shoes', 'shirts' ]
Zac
  • 1,010
  • 3
  • 11
  • 20