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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13336090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:10:51  来源:igfitidea点击:

Is there a Twig shorthand syntax for outputting conditional text

phptwig

提问by Justin

Is there a shorter syntax in Twig to output a conditional string of text?

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

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

Traditional php is even easier than this:

传统的 php 甚至比这更容易:

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

回答by mcriecken

This should work:

这应该有效:

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

Also, this is called the ternary operator. It's kind of hidden in the documenation: twig docs: operators

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

From their documentation the basic structure is:

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

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

回答by Raja Khoury

If you need to compare the value is equal to something you can do :

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

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

You can use the Elvis Operator inside twig :

您可以在 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

回答by danigore

The null-coalescing operatoralso working, like:

空凝聚运营商也在努力,比如:

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