Scottymeuk Scottymeuk - 1 year ago 118
PHP Question

Twig String == String

Can someone please explain how the following is possible: Very very odd issue (unless im missing something very simple):


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


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


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


Answer Source

This is easily reproductible :

{% set nav = true %}
{% if nav == "top" %}
{% 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.


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