40

如何检查字符串变量是否为空或为空,或者 Twig 中的空格字符是否已满?(最短可能,可能相当于 CSharp 的String.IsNullOrWhiteSpace()方法)

4

4 回答 4

59
{% if your_variable is null or your_variable is empty %}

应该检查变量是空还是空。

如果您想查看它是否为空或为空,只需使用not运算符。

 {% if foo is not null and foo is not empty %}

请参阅文档:

也许您通常对 twig 中的测试感兴趣。

于 2014-04-09T16:39:29.937 回答
44

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

{% if foo|length %}

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

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

参考 :

于 2014-04-10T07:33:51.200 回答
15

我宁愿只使用trimempty

{% if foo|trim is empty %} 

{% if foo|trim is not empty %} 

如果foo变量是,则empty评估为 true

  • 无效的
  • 错误的
  • 空数组
  • 空字符串
于 2014-09-12T10:40:23.003 回答
6

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

参考:

于 2014-04-09T19:25:43.733 回答