Is there a Twig shorthand syntax for outputting conditional text

♀尐吖头ヾ 提交于 2021-01-20 15:43:27

问题


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

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

Traditional php is even easier than this:

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

回答1:


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

From their documentation the basic structure is:

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



回答2:


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 :

{{  user ? 'is-user' }} 

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



回答3:


The null-coalescing operator also working, like:

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


来源:https://stackoverflow.com/questions/13336090/is-there-a-twig-shorthand-syntax-for-outputting-conditional-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!