Guillermo Gutiérrez
Guillermo Gutiérrez

Reputation: 17819

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

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)

Upvotes: 50

Views: 125916

Answers (4)

MikO
MikO

Reputation: 18741

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

Upvotes: 21

SirDerpington
SirDerpington

Reputation: 11460

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

Upvotes: 76

Alain
Alain

Reputation: 36964

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 :

Upvotes: 54

Guillermo Gutiérrez
Guillermo Gutiérrez

Reputation: 17819

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

Upvotes: 7

Related Questions