是否有用于输出条件文本的树枝速记语法



twig中是否有较短的语法来输出条件的文本字符串?

<h1>{% if not info.id %}create{% else %}edit{% endif %}</h1>

传统的PHP比这更容易:

<h1><?php info['id']? 'create' : 'edit' ?></h1>

这应该有效:

{{ not info.id ? 'create' : 'edit' }}

另外,这称为三元运算符。文档中隐藏了某种:树枝文档:操作员

从他们的文档中,基本结构是:

{{ foo ? 'yes' : 'no' }}

如果您需要比较值等于您可以做的事情:

{{  user.role == 'admin' ? 'is-admin' : 'not-admin' }}

您可以在树枝内使用猫王操作员:

{{  user ? 'is-user' }} 
{{  user ?: 'not-user' }} // note that it evaluates to the left operand if true ( returns the user ) and right if not

null-coalescing操作员也可以工作,例如:

{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}

最新更新