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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:15:47  来源:igfitidea点击:

Check if string variable is null or empty, or full of white spaces

stringtwigisnullorempty

提问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 notoperator.

如果你想看看它是不是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 |lengthis safer as the "0"|trimexpression will evaluates to false.

但我认为|length更安全,因为"0"|trim表达式的计算结果为 false。

References :

参考 :

回答by MikO

I'd rather use just trimand empty:

我宁愿只使用trimempty

{% if foo|trim is empty %} 

{% if foo|trim is not empty %} 

emptyevaluates to true if the foovariable is:

的计算结果为真,如果foo的变量是:

  • null
  • false
  • empty array
  • empty string
  • 空值
  • 错误的
  • 空数组
  • 空字符串

回答by Guillermo Gutiérrez

{% if foo|trim %}seems to be enough (assuming that foois the variable to check). If foois not null, trimremoves whitespaces. Also, ifhandles 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:

参考: