Conditionals

Conditional statements are a foundation of basic programming. They allow you to react to varying circumstances in your websites data environment in a simple, flexible way. It’s easy to formulate an if statement in Liquid.

{% if item.title == 'Test Page' %}
  This is a test page.
{% endif %}

If you have an if/else situation, that’s easy as well.

{% if item.title == 'Test Page' %}
  This is a test page.
{% else %}
  This is not a test page.
{% endif %}

You can also test the opposite of an if by using an unless.

{% unless item.title == 'Test Page' %}
  This is not a test page.
{% endunless %}

There’s also an ifchanged tag, which will tell if the contents of the tag has changed since last output. This is great, for example, to display a date header in a list of blog posts only if the date has changed.

{% for post in site.recent_posts.20 %}
  {% ifchanged %}<h2>{{ post.published_at | date: '%B %d' }}</h2>{% endifchanged %}
  <h3>{{ post | link_to_item }}</h3>
  <p>{{ post.excerpt }}</p>
{% endfor %}

A case statement is a simple and effective way to provide many different results based on the value of one variable.

{% case item.children.size %}
  {% when 0 %}
    none
  {% when 1 %}
    one
  {% when 2 %}
    two
  {% else %}
    a few more...
{% endcase %}