是否有用于输出条件文本的Twig简写语法

Jus*_*tin 59 php twig

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

<h1>{% if not info.id %}create{% else %}edit{% endif %}</h1>
Run Code Online (Sandbox Code Playgroud)

传统的PHP比这更容易:

<h1><?php info['id']? 'create' : 'edit' ?></h1>
Run Code Online (Sandbox Code Playgroud)

mcr*_*ken 132

这应该工作:

{{ not info.id ? 'create' : 'edit' }}
Run Code Online (Sandbox Code Playgroud)

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

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

{{ foo ? 'yes' : 'no' }}
Run Code Online (Sandbox Code Playgroud)

  • 在三元组中你为什么要这样做?{{not info.id?'create':'edit'}}只需以简单的方式应用逻辑.{{info.id?'edit':'create'}}'not'操作只会混淆问题 - 你必须指定两个结果字符串,为什么在不需要时通过否定来使代码变得更难读? (5认同)
  • @khaled_webdev这可以通过检查foo | default来解决. (2认同)

Raj*_*ury 27

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

{{  user.role == 'admin' ? 'is-admin' : 'not-admin' }}
Run Code Online (Sandbox Code Playgroud)

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

{{  user ? 'is-user' }} 

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


dan*_*ore 6

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

{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}
Run Code Online (Sandbox Code Playgroud)