检查字符串变量是空或空,还是满是空格

Gui*_*rez 31 string isnullorempty twig

如何在Twig中检查字符串变量是空或空,还是填充空格字符?(可能最短,可能等同于CSharp的String.IsNullOrWhiteSpace()方法)

Sir*_*ton 46

{% if your_variable is null or your_variable is empty %}
Run Code Online (Sandbox Code Playgroud)

应该检查变量是null还是空.

如果你想看看它是不是 null或空只使用not运营商.

 {% if foo is not null and foo is not empty %}
Run Code Online (Sandbox Code Playgroud)

查看文档:

也许你可能会对树枝上的测试感兴趣.

  • 我不是'twig`专家,但不应该是`{%if if foo is not null`**and**`foo is not empty%}`` 否则看起来总是如此. (3认同)

Ala*_*blo 32

已有很好的答案,但我也给了我2美分:

{% if foo|length %}
Run Code Online (Sandbox Code Playgroud)

我受到了@GuillermoGutiérrez的过滤技巧的启发.

但我认为|length更安全,因为"0"|trim表达式将评估为false.

参考文献:


Mik*_*ikO 12

我宁愿只使用修剪:

{% if foo|trim is empty %} 

{% if foo|trim is not empty %} 
Run Code Online (Sandbox Code Playgroud)

如果 foo变量为: empty,则求值为true:

  • 空值
  • 空数组
  • 空字符串


Gui*_*rez 6

{% if foo|trim %}似乎就足够了(假设这foo是要检查的变量)。如果foo不为空,则trim删除空格。此外,将if空字符串或 null 处理为 false,否则处理为 true,因此不需要更多。

参考: