Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

If Statements with "Tests"

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

But when we try the contact page, it blows up

Uncaught exception Twig_Error_Runtime with message "Variable backgroundColor does not exist in _banner.twig at line 5"

We're not passing a backgroundColor in the include call in contact.twig, so Twig gets angry! We can of course pass this variable to the template. But instead, let's check to see if the variable is defined in the _banner.twig template, and default to lightblue if it is not. To do this, we can use an if statement and a special defined test.

{# templates/_banner.twig #}

{% if backgroundColor is defined %}
    {# ... do something here #}
{% endif %}

Let's also see another new Twig tag called set, which sets a new variable.

{# templates/_banner.twig #}

{% if backgroundColor is defined %}
    {% set backgroundColor = backgroundColor %}
{% else %}
    {% set backgroundColor = 'lightblue' %}
{% endif %}

<div class="well" style="background-color: {{ backgroundColor }};">
    <h3>Save some Krill!</h3>

    <p>Sale in summer suits all this weekend! {{ pageData.title }}</p>
</div>

Try out both pages in the browser. Awesomesauce!

Let's look again at the if background is defined. Normally an if statement says something like if foo != 'bar' or if isPublished == true. That all works totally fine in Twig.

But in addition to == and != and the others, you can say is and follow that by a word like defined, even, odd, empty or several other words. These are called tests, and they're listed once again right back on the main Documentation page of the Twig website.

Go Deeper!

A list of all of the operators (e.g. /, *, ==, etc) can be found on the Twig Documentation.

For example, instead of using the length filter and seeing if the number of items in the products collection is zero, we could say if products is empty:

{# template/homepage.twig #}
{# ... #}

{% if products is empty %}
    <div class="alert alert-error span12">
        It looks like we're out of really awesome-looking penguin clothes :/.
    </div>
{% endif %}

If for some reason we wanted to know if the total number of products were even, we could use the length filter to get the number, then check that the number is "even" by using the even test:

{% if products|length is even %}
    <p>
        There are an even number of products
    </p>
{% endif %}

The tests are easy to use and can shorten the code needed to do some things, so don't forget about them!

Negating a Test

You can also negate a test by using the not keyword. We can use this to simplify our code from earlier:

{# templates/_banner.twig #}

{% if backgroundColor is not defined %}
    {% set backgroundColor = 'lightblue' %}
{% endif %}

<div class="well" style="background-color: {{ backgroundColor }};">
    <h3>Save some Krill!</h3>

    <p>Sale in summer suits all this weekend! {{ pageData.title }}</p>
</div>

Awesome! At this point, you know a lot of tools in Twig. Let's keep going and learn some more.

Leave a comment!

6
Login or Register to join the conversation

In the challenge #2 I've written condition like this
{% if quantityRemaining is defined and quantityRemaining <b>is even</b> %}

And it showed me an error, that the expected code was
{% if quantityRemaining is defined and quantityRemaining <b>is not odd</b> %}

It will be great if you allow the first option to pass validation :)

Reply

Hey horlyk!

Ha! Great point - thanks for telling us - we'll see if we can make that grading a bit smarter. Your "is even"... even looks better ;).

Cheers!

1 Reply
Default user avatar
Default user avatar Krzysztof | posted 5 years ago

It is worth mentioning here that default filter is an alternative to if else statements. http://twig.sensiolabs.org/...

{{ backgroundColor|default('lightblue') }}

Reply

Yes! That's a clever way to use the default filter indeed! You can also do {{ backgroundColor ? backgroundColor : 'lightblue' }}, but in this simple case, default is way cooler :p

Cheers!

Reply
Default user avatar

There's a typo in the Answer to Challenge #2 after this video - line #6 on _layout.twig should be 'quantityRemaining' not 'quantityRemaning' (it's missing an 'i' in the variable name)

Reply

Hey Goz,

Wow, it was difficult to find but you nailed it, good work! Thanks for this report, I fixed it in https://github.com/knpunive... with our internal tool.

Cheers!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial uses Twig 1. There are newer versions of Twig, but they don't contain significant differences. So, Twig on!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": []
}
userVoice