Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing variable equality 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.

So the only way I've found of comparing integers is to convert them both to strings:
{% if var1|lower is sameas(var2|lower) %}

like image 706
Sam Avatar asked Nov 29 '10 11:11

Sam


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.

Is not equal to in twig?

Twig != is a comparison operator. You can use != to compare any two things that php lets you compare, and what you get back is a boolean.

How do you use variables in twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .


2 Answers

As far as I'm aware Twig supports all of the standard logical operators ==, !=, <, >, >=, and <=. Also, your first example {% if var1 = var2 %} does not check for equality, it assigns var2 to var1, you might want to change it to the comparison operator ==.

The Twig sameas built in test, is essentially a strict type comparison operator ===, hence why they both need to be strings in your example.

like image 157
Russell Dias Avatar answered Sep 20 '22 18:09

Russell Dias


If you are comparing value which have a numeric value you can use:

{% if (psong.songid) ==(song.id) %} 
like image 39
webdeveloper Avatar answered Sep 23 '22 18:09

webdeveloper