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)
Asked
Active
Viewed 1.1e+01k times
49

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 Answers
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 not
operator.
{% 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
-
3I'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
-
1
-
@alanTiemblo - the most voted answer, I'd say. Still imho :-) – Marco Faustinelli Aug 29 '15 at 05:29
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