twig - Check if string variable is null or empty, or full of white spaces

ID : 131306

viewed : 9

Tags : stringtwigisnulloremptystring

Top 5 Answer for twig - Check if string variable is null or empty, or full of white spaces

vote vote

92

{% if your_variable is null or your_variable is empty %} 

should check whether the variable is null or empty.

If you want to see if it's not null or empty just use the notoperator.

 {% if foo is not null and foo is not empty %} 

See the docs:

Perhaps you might be interested in tests in twig generally.

vote vote

86

There are already good answers, but I give my 2 cents too:

{% if foo|length %} 

I was inspired by @GuillermoGutiƩrrez's filter trick.

But I think |length is safer as the "0"|trim expression will evaluates to false.

References :

vote vote

79

I'd rather use just trim and empty:

{% if foo|trim is empty %}   {% if foo|trim is not empty %}  

empty evaluates to true if the foo variable is:

  • null
  • false
  • empty array
  • empty string
vote vote

63

{% if foo|trim %} seems to be enough (assuming that foo is the variable to check). If foo is not null, trim removes whitespaces. Also, if handles empty string or null as false, and true otherwise, so no more is required.

References:

vote vote

55

Top 3 video Explaining twig - Check if string variable is null or empty, or full of white spaces

Related QUESTION?