Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 204
Guillermo Gutiérrez Avatar asked Apr 09 '14 16:04

Guillermo Gutiérrez


People also ask

How do you know if a string is null or whitespace?

To find out a string is null or just contents white space, you can use a similar method: string. IsNullOrWhiteSpace(), which can pretty much be used in the same way as the string. IsNullOrEmpty.

How do you check if a string is a whitespace?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

Is empty string considered whitespace?

First you should know the difference between empty string and a white space. The length of a white ' ' space is 1 . An empty string '' will have a length zero.

Is null or whitespace Java?

We consider a string to be empty if it's either null or a string without any length. If a string only consists of whitespace, then we call it blank. For Java, whitespaces are characters, like spaces, tabs, and so on.


1 Answers

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

  • empty
  • null
  • "is" operator
  • logical operators like "not"

Perhaps you might be interested in tests in twig generally.

like image 187
SirDerpington Avatar answered Oct 25 '22 07:10

SirDerpington