在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)
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)
空合并运算符也可以工作,例如:
{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
66058 次 |
最近记录: |