75

Twig 中是否有更短的语法来输出条件字符串?

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

传统的 php 比这更容易:

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

3 回答 3

158

这应该有效:

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

此外,这称为三元运算符。它有点隐藏在文档中:twig docs: operator

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

{{ foo ? 'yes' : 'no' }}
于 2012-11-11T22:29:02.777 回答
37

如果您需要比较该值是否等于您可以执行的操作:

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

您可以在 twig 中使用 Elvis Operator:

{{  user ? 'is-user' }} 

{{  user ?: 'not-user' }} // note that it evaluates to the left operand if true ( returns the user ) and right if not
于 2017-01-25T19:08:35.750 回答
4

合并运算符也可以工作,例如:

{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}
于 2019-05-01T18:25:02.693 回答