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)
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.
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.
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.
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.
{% 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With