Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do string comparison operators work in Twig?

Tags:

php

twig

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.

like image 375
Scottymeuk Avatar asked Apr 24 '13 18:04

Scottymeuk


People also ask

How do you compare two variables in twig?

In twig, is there an easy way to test the equality of 2 variables? {% if var1 = var2 %} isn't valid, {% if var1 is sameas(var2) %} only works if both are a strings... (from docs) "sameas checks if a variable points to the same memory address than another variable", like thats useful.

Can you use comparison operators with strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.

What is a string comparison?

string= compares two strings and is true if they are the same (corresponding characters are identical) but is false if they are not. The function equal calls string= if applied to two strings. The keyword arguments :start1 and :start2 are the places in the strings to start the comparison.


1 Answers

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.

like image 131
Alain Tiemblo Avatar answered Sep 28 '22 12:09

Alain Tiemblo