Search through more than a hundred articles on every aspect of User.com

Dawid Tyburek
Written by Dawid Tyburek

Conditional Statements

Using if statements


Introduction

In our app, you can render different data based on the user's attributes. For example you might have a company with different level Employees and you want to send one type of communication but covering different topics. You can do that using if statements.

Use cases

  • Let's say, you have Subscription Plans, some of them containing word 'Monthly', some of them 'Yearly'. You can simply create one email message with if statements and send this email to your database and it will get rendered properly depending who the receiver is! Saving you lots of time creating and styling several messages.


Code in the email message:

Will get rendered for example as:

  • If you run a Car Sharing Company you might want to send a different message based of the favourite rental car or the time somebody spent using your fleet. Just prepare different versions of the message and use desired attribute within the statement.


Code in the email message:

Will get rendered for example as:

if

The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, is not a false boolean value or is equal to aspecified value) the contents of the block are output.

{% if receiver.employee_number %}
Congratulations on getting {{receiver.employee_number}} employees!
{% else %}
Click here to learn how to hire new specialists
{% endif %}

Elif and Boolean operators

There is also a more advanced way to use "If" statements. When your statement block contains "elif" statements then the value under the first "true" statement will be executed. 

{% if receiver.first_name and receiver.last_name %}
Hello {{ receiver.first_name }} {{ receiver.last_name }}
{% elif receiver.last_name %}
Hello Mr. {{ receiver.last_name }}
{% else %}
Hello our dear Friend!
{% endif %}

As you can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional.

Other operators

If statements may also use the operators ==, !=, <, >, <=, >=, in, not in, is, and is not.

{% if receiver.purchased_products >= 15 %}
Gee, thanks!
{% elif receiver.purchased_products < 10 %}
We can see love for the brand growing and we love it!
{% endif %}


{% if receiver.job_title != "CEO" %}
Learn this great trick to be your own boss!
{% else %}
Whoah, congratulations!
{% endif %}

Complex statements

All of the above can be combined to form complex expressions.

{% if receiver.revenue == 100 or receiver.revenue == 150 %}
Here is your daily spending
{% else %}
Click here to start spending your money!
{% endif %}

Related articles


Categories: