2
votes

I am just getting into some liquid template coding on a Shopify site. How do I use the for-loop index/variable when defining variable names in assign or capture tags? ie: I'm trying to condense the code to create multiple link menus from sequentially numbered settings, where [i] would be a number between 2 and 4 in the settings key.

What is the proper syntax to insert that number into a) a tag like an if statement or assign. b) interpolated text like in the h3 element below. c) a nested/bracketed key statement (sorry if that's not what its called, i'm still learning), like in the second for statement.

{% for i in (2..4) %}
    {% if settings.footer_quicklinks_enable[i] %}
        <div class="grid-item medium--one-half large--three-twelfths">
          <h3>{{ 'layout.footer.quick_links{{i}}' | t }}</h3>
          <ul>
            {% for link in linklists[settings.footer_quicklinks_linklist[i]].links %}
              <li><a href="{{ link.url }}">{{ link.title }}</a></li>

            {% endfor %}
          </ul>
        </div>
    {% endif %}
    {% endfor %}
1

1 Answers

2
votes

You need to use the square bracket notation instead of dot notation.

Create a string containing the variable name (with assign or capture), then use square bracket notation to access the setting with that name.

For example:

{% capture var %}footer_quicklinks_enable_{{i}}{% endcapture %}
{% if settings[var] %}      

Also see this similar answer.