49

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)

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
  • Sorry to all, I reverted the question to the original statement, as the answer was chosen based on it. I modified it in a not so lucid moment of mine to look like a very similar but not exactly the same question. – Guillermo Gutiérrez Sep 12 '14 at 13:55

4 Answers4

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

SirDerpington
  • 11,260
  • 4
  • 49
  • 55
  • 3
    I'm not `twig` specialist, but shouldn't it be `{% if foo is not null ` **and** `foo is not empty %}`? Otherwise seems like it will be always true. – DarkWanderer Apr 10 '14 at 07:37
  • 1
    @SirDerpington is the `foo is (not) null` part still necessary? Twig documentation states that `empty` also checks if the value equals `null` – sschwei1 Jun 20 '22 at 11:40
  • 1
    @sschwei1 that's a good catch. According to the documentation that's indeed true. Not sure how it was back in 2014 though – SirDerpington Jun 20 '22 at 20:11
52

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 :

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
20

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
MikO
  • 18,243
  • 12
  • 77
  • 109
7

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

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116