Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a for loop in liquid with range

I am attempting to have a for loop in my template to loop through each letter of the alphabet, and if the first letter of the alphabet is found, print out that data.

I cannot find a way to do this, i know how to do this in PHP, but cannot get it to work in liquid.

{% for range('a','z') as $i %}   

    {% if first_letter == $i %}

        {% unless first_letter == current %}

            <li class="test"><h2 id='{{ first_letter }}'>{{ first_letter }}</h2> </li>

        {% endunless %}

        <ul><li class="test"> {{ product_vendor | link_to_vendor  }} </li>    </ul>

        {% assign current = first_letter %}

    {% endif %}
{% endfor %}

The top two lines is what is not working here, i know the syntax is incorrect, but i cannot figure out how to get this to work.

like image 706
Dom Greenslade BSc Avatar asked Oct 19 '22 17:10

Dom Greenslade BSc


1 Answers

The syntax for ranges in liquid for loops is here in the Shopify docs:

{% assign num = 4 %}
{% for i in (1..num) %}
  {{ i }} 
{% endfor %}

{% for i in (3..5) %}
  {{ i }} 
{% endfor %}

However, you can only use numbers in the range, not strings.

Have you seen this article? Maybe that approach would work in your situation.

Edit: Updated link for above article.

like image 149
Steph Sharp Avatar answered Oct 22 '22 19:10

Steph Sharp