Loop through products in a variable-defined collection

Topic summary

Core Issue:
A developer is trying to create a “Pairs Well With” section on product pages that displays items from the product’s “parent” collection (defined as the collection with the fewest products). They successfully identified the parent collection using a variable but cannot use that variable within a for loop to iterate through products.

Key Question:
How to reference a dynamically-assigned collection variable in Liquid’s for loop syntax (e.g., {% for product in collections[variable_name].products %})?

Solution Provided:
A community member (ri31) shared extensive testing results:

  • Square brackets around variables DO NOT work in Liquid object references
  • Dot notation with variables DOES work (e.g., collections.variable_name.products)
  • Multiple variables in one reference string initially failed, but ri31 later succeeded by chaining variables that don’t individually represent Liquid objects
  • Variables must be defined using assign before use
  • No quotation marks should surround variable names in object references

Status:
The discussion appears resolved with a working approach demonstrated through code examples and test results showing successful multi-variable references in for loops using dot notation.

Summarized with AI on November 3. AI used: claude-sonnet-4-5-20250929.

Since I can’t edit the previous reply, replying again.

I was now able to get multiple variables to work together to load a value in liquid. I think part of the secret is that none of these variables, by itself, represents any Liquid object in my store.

Here is the exact code and the first result.

CODE:

{%- assign key_part_1 = ‘brand’ -%}
{%- assign key_part_2 = ‘value’ -%}
{%- assign key_part_3 = ‘brand’ -%}
{%- assign multi_level_key = ‘brand.value.brand’ -%}
{%- assign repeater_filter = ‘Cipollini’ -%}
{%- assign repeated_object = ‘bike_guide’ -%}

Variable Data

key_part_1: {{key_part_1}}

key_part_2: {{key_part_2}}

key_part_3: {{key_part_3}}

repeater_filter: {{repeater_filter}}

repeated_object: {{repeated_object}}

Testing the variables inside a for loop

{%- for item in shop.metaobjects[repeated_object].values -%}

Test using one variable

item.brand: {{item.brand}}

item[key_part_1]: {{item[key_part_1]}}

item.key_part_1: {{item.key_part_1}}

Test using 2 variables

item.brand.value: {{item.brand.value}}

item[key_part_1][key_part_2]: {{item[key_part_1][key_part_2]}}

Test using 3 variables

item.brand.value.brand: {{item.brand.value.brand}}

item[key_part_1][key_part_2][key_part_3]: {{item[key_part_1][key_part_2][key_part_3]}}

{%- assign item_key = item[key_part_1][key_part_2][key_part_3] -%}

The full item key is {{item_key}}

{%- if item_key == repeater_filter -%}

This item passed the filter.

{%- endif -%}
{%- endfor -%}

FIRST RESULT: