我该如何在Twig中检查字符串变量是否为null、空或只包含空格字符?(可能是最短的方式,类似于CSharp的
String.IsNullOrWhiteSpace()
方法)String.IsNullOrWhiteSpace()
方法){% if your_variable is null or your_variable is empty %}
应该检查变量是否为 null 或空。
如果你想要检查它不是 null 或空,只需使用 not
运算符。
{% if foo is not null and foo is not empty %}
查看文档:
也许你会对Twig中的测试感兴趣。
**and**
foo is not empty %}”才对吧?否则看起来似乎会一直为真。 - DarkWanderernull
。 - sschwei1{% if foo|trim %}
似乎就足够了(假设要检查的变量为foo
)。如果 foo
不是 null,则 trim
会删除空格。此外,if
处理空字符串或 null 作为 false,否则为 true,因此不需要更多的操作。
参考资料: