Easiest way to create an array of images?

I know this might be a basic question, but I’m frustrated that this isn’t easier to do in Liquid like it would be in JavaScript.

What’s the simplest way to create an array of images in Liquid?

For example, I have cta_image_1, cta_image_2, and cta_image_3, but I can’t use blocks–for whatever reason. I need to dynamically render only the images that are populated—if someone adds two images, I want to display just those two without breaking the layout.

In JavaScript, I’d just push them into an array, loop through, and render them. But in Liquid, when I try to build a list, it cuts off the image src string, so I can’t use it with something like the image_tag filter.

I’ve tried capture and normal assigning, splitting, etc. with same results. I feel like I’ve done this in the past, but can’t think of how I did it. Any suggestions?

Hello,

There’s the image_url filter. However, this filter works in the context of section/block which does not apply to your question. It is still applicable with metaobjects. For example:

{% for image in metaobjects.my_definition.entry-1.img_list.value %} 
    <img src ="{{image | image_url: width: 100, height: 100 }}" /> 
{% endfor %}

In this case I created a metaobject definition called my_definition which would have a img_list as one of its fields. Then I created an entry called entry_1 where I linked the values to my shopify media files.

Refer to these docs to learn more about metaobjects: https://help.shopify.com/en/manual/custom-data/metaobjects/building-a-metaobject.


Another alternative is to have a list of source URLs and use the image_tag filter. For example:

{% assign images = "https://cdn.shopify.com/s/files/...,https://cdn.shopify.com/s/files/..., https://path.to.myimage.com/123" | split: "," %} 

{% for image in images %} 
   {{image | image_tag}} 
{% endfor %}

Refer to image_tag filter docs here: https://shopify.dev/docs/api/liquid/filters/image_tag


My recommendation is to use metoabject definition with a list of files (or list of URLs) and use that in your liquid code. It is more dynamic than a hardcoded list of URLs and does not use blocks/sections.

1 Like