45

How is this possible? It seems to be a very very odd issue (unless I’m missing something very simple):

Code:

{{ dump(nav) }}
{% if nav == "top" %}
    <div class="well">This would be the nav</div>
{% endif %}

Output:

boolean true
<div class="well">This would be the nav</div>

Screenshot

Basically, it is outputting if true, but it’s not meant to be checking for true.

2
  • Sorry, figured it would not make a difference with only 4 lines of code.
    – Scottymeuk
    Apr 24, 2013 at 18:16
  • 4
    Questions you post on here should always be selfcontained. Once the links die your question is useless to future readers.
    – PeeHaa
    Apr 24, 2013 at 18:22

2 Answers 2

58

This is easily reproductible :

{% set nav = true %}
{% if nav == "top" %}
ok
{% endif %}

Displays ok.

According to the documentation :

Twig allows expressions everywhere. These work very similar to regular PHP and even if you're not working with PHP you should feel comfortable with it.

And if you test in pure PHP the following expression :

$var = true;
if ($var == "top") {
  echo 'ok';
}

It will also display ok.

The point is : you should not compare variables of different types. Here, you compare a bool with a string : if your string is not empty or if it does not contains only zeros, it will evaluate to true.

You can also have a look to the PHP manual to see how comparison are made with different types.

Edit

You can use the sameas test to make strict comparisions, and avoid type juggling matters.

1
  • Thank you for your answer. I am not actually using the code like this, but i stumbled across it while i was changing things from "display_nav" to allow a position to be specified. I was not sure if it was a bug, or if i was just missing something. Thank you for your detailed reply.
    – Scottymeuk
    Apr 24, 2013 at 18:30
0

If someone needs to negate result of the string comparison statement use next construction:

{% set is_training = course_type == 'training' %}
...
{% if not is_training %}
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.