Using the null-coalescing Operator in Twig


Introduction

Recently, I wanted to simplify my Twig code by only showing a filled in “Other” value when an “Other” checkbox had been selected and the Other value filled in within a Symfony form that I developed. You can read up on how I developed that form in my Simplified Web Development with JSON and the Twig Ternary Operator.

My JSON code looks like the following:

{
   "License": true,
   "Transit": true,
   "No_Issues": false,
   "Friend": true,
   "Car": false,
   "Other": true,
   "Other_Value": "skateboard"
}

Where in this case “Other” is set to “true”, so Other was selected and the Other Value was filled in and “skateboard” was entered in the form.

Rending in Twig

So now in my Twig template, I can use the null-coalescing operator which is in the form:

{{ foo ?? 'no' }}

The above code means, if foo is NOT defined, then show ‘no’. So in my case for the JSON I was using, I used the null-coalescing operator in my Twig template like so:

Other: {{ transport['Other_Value'] ?? '' }}

Which will simply display “skateboard” in this case. The code is very simple and is easy to re-use and support.

Hope this helps someone!

 

Advertisements

About Alvin Bunk
Hi, I'm a software developer at Taft College.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: