For Loop in Variable Name Liquid not working?

Viewed 39

I encounter this issue when I don't have any array, only have a list of variables.

{% assign test_1 = 'A' %}
{% assign test_2 = 'B' %}
{% assign test_3 = 'C' %}
{% assign test_4 = 'D' %}
{% assign test_5 = 'E' %}

{% for i in (1..5) %}
   {% capture my_index %}{{forloop.index}}{% endcapture %}
   {{test_[my_index]}}
{% endfor %}

Result: I got empty result.

Expected Result:

A B C D E
1 Answers

The result is empty because there is an error.

test_ is not defined. You can't use it as if it was an array or a dictionary.

Anyway, as the code is structured, it is impossible to retrieve the values of test_1, test_2.... What you can do is

{% assign test = 'A,B,C,D,E' | split: ',' %}


{% for i in (0..5) %}
    {{ test[i] }}
{% endfor %}

Note that there is no way to create an array except use a function like split.

Also, keep in mind that {% capture %} is just a fancy assign. I'm not saying that is not useful, but it's not (as I thought for a while) a sort of eval. It just assign the value inside of it, to the variable specified.

Related