Video outline

Unless is a control flow tag we can use to determine whether a certain piece of code should be rendered.

Other examples of control flow tags having similar purposes are if, else, elsif, and case/when.

An unless statement is used to check whether a certain condition has been met. Any code or content which has been placed inside the unless statement will NOT be shown/executed in the template if that condition is fulfilled.

The unless statement is the opposite of an if statement.

Syntax

Typing: unless + tab

will result in:

{% unless condition %}content{% endunless %}

which sets out the ‘frame’ for an unless statement.

An unless statement consists of three parts.

  • The first part is the opening tag, which includes the condition. The condition usually contains two variables and an operator.
  • The second part of the unless statement is the code that should not be rendered, in case the statement is true. Keep in mind that an unless statement is the opposite of an if-statement.
  • The third part is the closing tag, which is required syntax to make your unless statement work correctly.

Condition

The condition consists of 3 parts:

  • the variable containing data that needs to be checked
  • the operator used to compare data: <, >, ==, etc.
  • The value to which the variable is compared:
    • Can be a value (e.g. 235,46522)
    • Can be a boolean (true or false)
    • Usually a variable as well

Here I will show you an example of an unless statement. In the example, the text ‘profit’ is displayed always, except in the case when the condition in the unless statement is met.

Here, the value is 1000 so the condition is not met. Therefore the text ‘profit’ is displayed.

{% assign total_result = 1000 %}

{% unless total_result < 0 %}
  profit
{% else %}
  loss
{% endunless %}

Here you can see that when the value is negative, the condition is met so we end up in the else scenario. The else scenario in an unless statement, can be compared to an if-statement scenario on the same condition.

{% assign total_result = -1000 %}

{% unless total_result < 0 %}
  profit
{% else %}
  loss
{% endunless %}

Conclusion

  • An unless statement is used to only execute code when a certain condition is NOT fulfilled
  • An unless statement is the opposite of an if-statement
  • The else-scenario in an unless statement provides the code rendered when the condition does apply