Identically (===) in Twig

Here's the PHP code:

if ($var===0) {do something}

It "does something" only when $varit is actually 0 (and if it is $varnot installed, it does not work, so everything is in order).

However, Twig does not support the === operator, and if I write:

{% if var==0 %}do something{% endif %}

he "does something" all the time (even if $varnot installed). To fix this, I wrote this code:

{% if var matches 0 %}do something{% endif %}

Is this the right way to do === comparison in Twig, or am I doing something wrong here? If it is wrong, how should it be fixed?

+4
source share
2 answers

You need to use same asin Twig for ===comparisons:

{% set var1=0 %}
{% set var2='0' %}

{% if var1 is same as( 0 ) %}
    var1 is 0.
{% else %}
    var1 is not zero.
{% endif %}

{% if var2 is same as( 0 ) %}
    var2 is 0.
{% else %}
    var2 is not 0.
{% endif %}

{% if var2 is same as( '0' ) %}
    var2 is '0'.
{% else %}
    var2 is not '0'.
{% endif %}

Here is the twigfade showing it in action:

https://twigfiddle.com/k09myb

same as, , ===. , !

+3

Twig ===, same as. .: https://twig.sensiolabs.org/doc/2.x/tests/sameas.html

, :

{% if var is same as(0) %}do something{% endif %}

, is defined, , ​​ .

+2

Source: https://habr.com/ru/post/1675790/


All Articles