Control flow

Control flow tags are fundamental elements of template languages that allow developers to create logic and conditional statements in their templates. This document provides an overview of control flow tags and how to use them effectively.

1. If, elsif, else, and endif

These tags ({% if %}, {% elsif %}, {% else %}, and {% endif %}) are used to create conditional statements that execute based on whether a condition is true or false.

1.1. If

The {% if %} tag is used to test a condition. If the condition is true, the code between the {% if %} and {% endif %} or {% else %} tags will be executed.

Example:

{% if product.available %}
  In stock
{% endif %}

1.2. elsif

The {% elsif %} tag is used to test an additional condition when the previous condition is false. It must be placed between {% if %} and {% else %} or {% endif %} tags.

Example:

{% if product.available %}
  In stock
{% elsif product.preorder %}
  Available for preorder
{% endif %}

1.3. else

The {% else %} tag is used to execute code when all previous conditions are false. It must be placed between {% if %} or {% elsif %} and {% endif %} tags.

Example:

{% if product.available %}
  In stock
{% else %}
  Out of stock
{% endif %}

1.4. endif

The {% endif %} tag is used to close the conditional statement started by an {% if %} tag.

2. for, endfor, break, and continue

These tags ({% for %}, {% endfor %}, {% break %}, and {% continue %}) are used to create loops that iterate over a collection of items.

2.1. For

The {% for %} tag is used to iterate over a collection of items and execute the code between {% for %} and {% endfor %} tags for each item.

Example:

{% for product in collection.products %}
  {{ product.title }}
{% endfor %}

2.2. endfor

The {% endfor %} tag is used to close the loop started by an {% for %} tag.

2.3. break

The {% break %} tag is used to exit a loop prematurely when a certain condition is met.

Example:

{% for product in collection.products %}
  {{ product.title }}
  {% if forloop.index == 5 %}
    {% break %}
  {% endif %}
{% endfor %}

2.4. continue

The {% continue %} tag is used to skip the remaining code in the loop and move on to the next iteration when a certain condition is met.

Example:

{% for product in collection.products %}
  {% if product.hidden %}
    {% continue %}
  {% endif %}
  {{ product.title }}
{% endfor %}

Summary

Control flow tags are essential for adding logic and conditional statements to your templates. By understanding and using the various control flow tags, such as if, elsif, else, endif, for, endfor, break, and continue, you can create dynamic and flexible templates that respond to different conditions and data inputs. This enables you to build more robust and customizable themes for your web applications.

Last updated