Re: How to increment a variable name?

Solved

How can I increment variable names in a loop?

dwightco
Excursionist
21 0 2

Let's say I have some variables that I need to repeat in a section.
Ex.

variable_1
variable_2
variable_3
variable_4
variable_5

And I need to call them, like:

block.settings.variable_1
block.settings.variable_2
block.settings.variable_3
block.settings.variable_4
block.settings.variable_5

And they need a schema reference, like:

        {
          "type": "text",
          "id": "variable_1"
        },
        {
          "type": "text",
          "id": "variable_2"
        },
        {
          "type": "text",
          "id": "variable_3"
        },
        {
          "type": "text",
          "id": "variable_4"
        },
        {
          "type": "text",
          "id": "variable_5"
        },


Is it possible to do this all in a loop where the number increases by 1 with every iteration?

I've tried increment/capture/cycle but I can't make it to work because I am not sure how to increment the variable and make it available to be called in liquid.

Thank you!


Accepted Solution (1)

IttantaTech
Shopify Partner
525 55 103

This is an accepted solution.

Hello @dwightco 

Try like this ,

{% for i in (1..5) %}
{% capture my_index %}{{forloop.index}}{% endcapture %}
<li>{{block.settings.variable_[my_index]}}</li> 
{% endfor %}

Thanks,
Ittanta Technologies Pvt. Ltd. | Shopify Expert
If reply is helpful, please Like and Accept Solution.
To hire us, contact us at info@ittanta.com

View solution in original post

Replies 2 (2)

IttantaTech
Shopify Partner
525 55 103

This is an accepted solution.

Hello @dwightco 

Try like this ,

{% for i in (1..5) %}
{% capture my_index %}{{forloop.index}}{% endcapture %}
<li>{{block.settings.variable_[my_index]}}</li> 
{% endfor %}

Thanks,
Ittanta Technologies Pvt. Ltd. | Shopify Expert
If reply is helpful, please Like and Accept Solution.
To hire us, contact us at info@ittanta.com
dwightco
Excursionist
21 0 2

Thanks for this! I didn't know you can use brackets inside liquid tags.

I am guessing this won't work in the schema/JSON?