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!