Ad

Dynamically Outputting Liquid Object Using Loop Index

- 1 answer

I have been trying to iterate an output of a section using variables, but I cannot find a way to output the liquid object dynamically by concatenating the index. images[i] is the id of the image that I set in the {% schema %} section.

{% for i in (1 .. 5) %}

{% if section.settings.images[i] != blank %}
    {{ section.settings.image[i] }}
{% endif %}

{% endfor %}
Ad

Answer

You were almost there.

You need to assign the handle/id, since at the moment images[i] points to an array of images which is not correct.

The code should be something like this:

{% for i in (1 .. 5) %}
  {% assign image_handle = 'images' | append: i %}
  {% if section.settings[image_handle] != blank %}
      {{ section.settings[image_handle] }}
  {% endif %}
{% endfor %}

Assuming that your images ID are called images1, images2, images3 etc..

PS:

I'm not sure of your full code, but if you have a section and if you're not using its blocks why don't you use them instead of predefined sections fields?

{%- for block in section.blocks -%}
  {%- if block.settings.image != blank -%}
    {{ block.settings.image | img_url: '600x' | img_tag }}
  {%- endif -%}
{%- endfor -%}

{% schema %}
{
  "name": "Images",
  "max_blocks": 5,
  "blocks": [
    {
      "type": "image",
      "name": "Image",
      "settings": [
        {
          "type": "image_picker",
          "id": "image",
          "label": "Image"
        }
      ]
    }
  ]
}
{% endschema %}
Ad
source: stackoverflow.com
Ad