a Sensio Labs Product

The flexible, fast, and secure
template engine for PHP

Tags » if

Questions & Feedback

License

Creative Commons License Twig documentation is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

ifΒΆ

The if statement in Twig is comparable with the if statements of PHP.

In the simplest form you can use it to test if an expression evaluates to true:

1
2
3
{% if online == false %}
    <p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %}

You can also test if an array is not empty:

1
2
3
4
5
6
7
{% if users %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

Note

If you want to test if the variable is defined, use if users is defined instead.

For multiple branches elseif and else can be used like in PHP. You can use more complex expressions there too:

1
2
3
4
5
6
7
{% if kenny.sick %}
    Kenny is sick.
{% elseif kenny.dead %}
    You killed Kenny! You bastard!!!
{% else %}
    Kenny looks okay --- so far
{% endif %}
This website is powered by PHP and Twig. The Twig logo is © 2010-2012 Sensio Labs