Building Solid Liquid Skills - Control Flow and Iteration Tags

Below is a summary of Liquid tags (Control flow, Iteration flow, Template, and CDS tags) and the output they produce on a website.

CONTROL FLOW TAGS

IF / ELSIF / ELSE

Note the spelling on the “ELSIF” tag.

{% if user.fullname == 'Victor Dantas' %}
  Hello, Victor.
{% elsif user.fullname == 'Anna Dantas' %}
  Hello, Mr. Smith.
{% else %}
  Not sure who you are, but you can become part the family!
{% endif %}

UNLESS

Similar to IF tag but block is displayed if condition is not met.

  {% unless user.fullname contains 'Dantas' %}
    <div class="well">
      <b>You are NOT PART of the clan!</b>
    </div>
  {% endunless %}

CASE

    {% assign value = 3 %}

    {% case value %}
    {% when 1 %}
        This is number ONE </br>
    {% when 2 %}
        This is number TWO </br>
    {% else %}
        Neither 1 nor 2... this number 3!!!! </br>
    {% endcase %}

OUTPUT

Neither 1 nor 2... this number 3!!!!


ITERATION TAGS

FOR

Consider the following array declaration as I show case a simple for loop and other for loops using different parameters.

{% assign speakers = 'Danish, Yash, Raz, Victor, Scott' | split: ',' %}

SIMPLE LOOP

    {% for speaker in speakers %}
        {{speaker}},
    {% endfor %}

OUTPUT

Danish, Yash, Raz, Victor, Scott,


LIMIT

{% for speaker in speakers limit:3 %}
    {{speaker}},
{% endfor %}

OUTPUT

Danish, Yash, Raz,


OFFSET

{% for speaker in speakers offset:3 %}
    {{speaker}},
{% endfor %}

OUTPUT

Victor, Scott,


REVERSED + CYCLE

{% for speaker in speakers reversed%}
  <a class= "btn {% cycle 'btn-default', 'btn-primary'%}"> {{speaker}} </a>
{% endfor %}

OUTPUT

Buttons.png

FORLOOP OBJECT

The forloop object is available inside of the for tag. Through this object you may now whether the active item in the iteration is the first or last item.

{% for speaker in speakers %}
  {{speaker}}
  {% if forloop.first%} **** {% endif %}
  {% if forloop.last == false%}<b>,</b> {% endif %}
{% endfor %}

OUTPUT

Danish **** , Yash , Raz , Victor , Scott


Victor Dantas