Click here to Skip to main content
15,894,343 members
Articles / All Topics

Using the null-coalescing Operator in Twig

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Apr 2017CPOL 2.9K  
How to use 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:

JavaScript
{
   "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:

JavaScript
{{ 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:

JavaScript
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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Taft College
United States United States
I’m a software developer. Currently I’m working at Taft College as a Programmer.

Comments and Discussions

 
-- There are no messages in this forum --