Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is identical (===) in Twig

Tags:

php

twig

Here's the PHP code:

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

It "does something" only when $var is actually 0 (and if $var is not set, it doesn't work, so everything is OK).

However, Twig doesn't support === operator, and if I write:

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

it "does something" all the time (even when $var is not set). In order to fix it, I wrote such a code:

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

Is it a proper way to do === comparison in Twig, or I did something wrong here? If it's wrong, how should it be fixed?

like image 865
Mindaugas Li Avatar asked Apr 27 '17 10:04

Mindaugas Li


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.


1 Answers

You need to use same as in 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 a twigfiddle showing it in operation:

https://twigfiddle.com/k09myb

Here is the documentation for same as also stating that it is equivalent to ===. Hope that helps you!

like image 193
Alvin Bunk Avatar answered Sep 25 '22 17:09

Alvin Bunk