skip to Main Content

I am using Shopify’s Liquid language to create some lists of content for my store, but I am having trouble getting the logic right with this if statement that I am using.

I am trying to assign classes to a li html element based on a few conditions so that I can eventually sort these into groups of 5 links later.

Firstly, I am checking that the linklist is less than or equal to 5 links if not, go on to the next one, are all the links equal to 10 or more, if not, go to the next, are the links equal to 15 etc etc.

I know my logic is not quite right somewhere, my code seems to end at the second elsif, even when my linklist has 20 or so links in them.

{% if linklists[footer_linklist-2].links.size <= 5 and linklists[footer_linklist].links == empty %}

   columns_1

{% elsif linklists[footer_linklist-2].links.size >= 10 and linklists[footer_linklist].links == empty %}

   columns_2

{% elsif linklists[footer_linklist-2].links.size >= 15 and linklists[footer_linklist].links == empty %}

   columns_3

{% endif %}

2

Answers


  1. You need to order your elsif in descending order. The >=10 in the first one will catch everything 10 or more (including 15, 20 etc.). Try this:

    {% if linklists[footer_linklist-2].links.size <= 5 and linklists[footer_linklist].links == empty %}
    
       columns_1
    
    {% elsif linklists[footer_linklist-2].links.size >= 15 and linklists[footer_linklist].links == empty %}
    
       columns_3
    
    {% elsif linklists[footer_linklist-2].links.size >= 10 and linklists[footer_linklist].links == empty %}
    
       columns_2
    
    {% endif %}
    
    Login or Signup to reply.
  2. Firstly you should check for the biggest size, then smaller and smaller, because now, if linklist size is for example 30, then it will go to columns_2, because 20 >= 10, so your code will assign value columns_2 and did not go anywhere else. Correct code should look something like this:

    {% if size >= 15 %} // all numbers greater or equal 15
        columns_4
    {% elseif size >= 10 %} // there you get numbers greater or equal 10, but smaller than 15
        columns_3
    {% elseif size > 5 %} // I added this, because what will happen if size is for example 7?
        columns_2
    {% else %} // any size smaller or equal 5
        columns_1
    {% endif %}
    

    You can of course made in revert order from detecting smaller size to bigger (which should be faster in your case):

    {% if size <= 5 %} // all numbers lower or equal 5
        columns_1
    {% elseif size <= 10 %} // there you get numbers lower or equal 10, but greater than 5
        columns_2
    {% elseif size <= 15 %} // all numbers lower or equal 15, but greater than 10
        columns_3
    {% else %} // any size greater than 15
        columns_4
    {% endif %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search