Justin
Justin

Reputation: 4263

Is there a Twig shorthand syntax for outputting conditional text

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>

Upvotes: 86

Views: 113142

Answers (4)

Dario Zadro
Dario Zadro

Reputation: 1284

Often, you can use default for this job.

{{ foo|default('bar') }}

Which is roughly equivalent to:

<?php echo isset($foo) ? $foo : $bar; ?>

It may not exactly be what the OP wanted, but I think it will come in handy for a closely related need with others.

Upvotes: 0

danigore
danigore

Reputation: 416

The null-coalescing operator also working, like:

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

Upvotes: 6

Raja Khoury
Raja Khoury

Reputation: 3195

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

Upvotes: 43

mcriecken
mcriecken

Reputation: 3297

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' }}

Upvotes: 181

Related Questions