string 检查字符串变量是否为空或空,或充满空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22968427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if string variable is null or empty, or full of white spaces
提问by Guillermo Gutiérrez
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)
如何在 Twig 中检查字符串变量是否为空或空,或是否充满空格字符?(尽可能短,可能相当于 CSharp 的String.IsNullOrWhiteSpace()
方法)
回答by SirDerpington
{% 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 notnull or empty just use the not
operator.
如果你想看看它是不是null或空只使用not
运营商。
{% if foo is not null and foo is not empty %}
See the docs:
查看文档:
Perhaps you might be interested in tests in twiggenerally.
回答by Alain Tiemblo
There are already good answers, but I give my 2 cents too:
已经有很好的答案,但我也给了我 2 美分:
{% if foo|length %}
I was inspired by @GuillermoGutiérrez's filter trick.
我的灵感来自@GuillermoGutiérrez 的过滤技巧。
But I think |length
is safer as the "0"|trim
expression will evaluates to false.
但我认为|length
更安全,因为"0"|trim
表达式的计算结果为 false。
References :
参考 :
回答by MikO
回答by Guillermo Gutiérrez
{% 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.
{% if foo|trim %}
似乎就足够了(假设这foo
是要检查的变量)。如果foo
不为空,则trim
删除空格。此外,将if
空字符串或 null 处理为 false,否则处理为 true,因此不需要更多。
References:
参考: