Conditions
If
Sometimes you want a specific piece of content to appear based on the content of a dynamic data. This is a very good use-case for an if
:
{% if user.age < 18 %}
<p>As a minor you need to obtain your parents approval.</p>
{% endif %}
If / Else
In some other occasion you might need to choose between two opposed options:
{% if client.type == "company" %}
<p>{{client.companyName}} is represented by {{client.name}}.</p>
{% else %}
<p>{{client.name}} represents herself only.</p>
{% endif %}
Other keywords
For more advanced cases you might be interested in the following keywords.
The unless
keyword acts as the exact inverse of an if
:
{% unless user.isBob %}
<p>Your are not Bob!</p>
{% endunless %}
The if … elsif … else
succession allows a bit more cases:
{% if client.isBob %}
<p>You are Bob.</p>
{% elsif client.type == "person" %}
<p>You are a person.</p>
{% else %}
<p>You may be… a monkey.</p>
{% endif %}
When a dynamic data may contain several values and the content needs to change according to it, the case … when … else
construct might be a good fit:
{% case client.type %}
{% when "company" %}
<p>Interested in our B2B offers?</p>
{% when "person" %}
<p>Interested in our B2C offers?</p>
{% else %}
<p>Interested in our offers?</p>
{% endcase %}