Question

How can I check if a string variable is null or empty, or full with space characters in Twig? (Shortest possible, maybe an equivalent to CSharp's String.IsNullOrWhiteSpace() method)

Was it helpful?

Solution 2

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 :

OTHER TIPS

{% 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.

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

{% 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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top