Conditional Logic

Prev Next

Conditional logic controls which content is rendered based on whether a given condition evaluates to true or false. In Liquid, this is implemented through {% if %}, {% elsif %}, {% else %}, and {% unless %} tags, allowing templates to produce different outputs depending on the state of a variable or expression. This enables dynamic, personalized content without duplicating template code.

Truthy / Falsy

Only nil, false, and "" are treated as false. Everything else, including 0, " ", and empty arrays ([]), is truthy.

{# Wrong — 0 IS truthy, the "else" branch never runs when count = 0 #}
{% if count %}
  You have {{ count }} items.
{% else %}
  No items.
{% endif %}

{# Correct #}
{% if count > 0 %}
  You have {{ count }} items.
{% else %}
  No items.
{% endif %}

Check for blank before other conditions

Always check that a variable has a value before comparing it, to avoid unexpected behavior with unset attributes.

{# Safe — checks existence first #}
{% if c_loyalty_tier != blank and c_loyalty_tier == "gold" %}
  Gold offer.
{% endif %}

{# Simpler when the comparison already handles blank safely #}
{% if c_loyalty_tier == "gold" %}
  Gold offer.
{% endif %}

Nested conditions

Use nested if blocks for logical grouping (parentheses are not supported).

{% if age >= 18 %}
  {% if c_loyalty_tier == "gold" or c_loyalty_tier == "silver" %}
    Adult loyalty member content.
  {% else %}
    Adult non-member content.
  {% endif %}
{% else %}
  This offer is for adults only.
{% endif %}

Custom attributes in conditions

Reference custom attributes in conditions with c_ prefix.

{% if c_preferred_store != blank %}
  Your nearest store: {{ c_preferred_store }}
{% endif %}

{% if c_membership_date != blank %}
  Member since: {{ c_membership_date | time_format: "MMMM YYYY" }}
{% endif %}