if

The if tag is used to test and see if an expression evaluates to a desired value. 

The format for the tag is:

{% if test %}
{% endif %}

Examples

A simple example to see if the variable matches a value.

{% if category.categoryName == 'Photos' %}
    <p>You are looking at photos!</p>
{% endif %}

Test to see if the variable is a boolean value.

{% if offline == true %}
    <p>We are offline now. Come back later.</p>
{% endif %}

Test and see if a variable is defined and not empty.

{% if color %}
    <p>My favorite color is {{ color }}</p>
{% endif %}

Test and see if an array value is defined and not empty

{% if category.posts %}
    {% for post in category.posts %}
        <p><a href="{{ post.url }}">{{ post.postTitle }}</a></p>
    {% endfor %}
{% endif %}

If you just want to test and see if the variable is defined then use the defined test instead.

{% if category.posts is defined %}
{% endif %}

Negative tests

To perform a negative test you would use the not operator.

{% if not post.comments %}
    <p>No comments have been added yet</p>
{% endif %}

{% if not user.subcribed %}
    <p>You are not subscribed yet.</p>
{% endif %}

{% if color not in favoriteColors %}
    <p>{{ color }} is not a favorite color</p>
{% endif %}

{% if images is not defined %}
    <p>No images are available.</p>
{% endif %}

Multiple conditions

You can use and and or to perform multiple tests.

{% if weather == 'sunny' and temperature == 'warm' %}
    <p>It's a great day to go to the beach.</p>
{% endif %}

{% if food == 'cookie' or isChocolate == true %}
   <p>This is going to be good!</p>
{% endif %}

You can use && in place of and

{% if weather == 'sunny' && temperature == 'warm' %}
    <p>It's a great day to go to the beach.</p>
{% endif %}

You can use || in place of or.

{% if food == 'cookie' || isChocolate == true %}
   <p>This is going to be good!</p>
{% endif %}

else and elseif

You can use elseif to test other conditions and else to handle situations where the other tests don't pass.

elseif can use the same complex expressions that if can. 

{% if post.categories %}
    <p>Has categories</p>
{% else %}
    <p>No categories</p>
{% endif %}

{% if  _page.request.url == '/contact' %}
    <p>You're on the contact page</p>
{% elseif _page.request.url == '/about' %}
    <p>You're on the about page</p>
{% elseif _page.request.url|lower starts with '/help' %}
   <p>This is a help page</p>
{% elseif _page.request.url contains 'blog' %}
    <p>You're in the blog</p>
{% else %}
    <p>I don't know where you are.</p>
{% endif %}

Testing to see if a variable exists

If you are testing to see if a variable exists like this, {% if variable %} {% endif %}, then the following rules determine if the expression is true or false.

Value Boolean Evaluation
empty string false
numeric zero false
whitespace-only string true
empty array false
null false
non-empty array true
object true
true true
false false

< Back to the list of tags