New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding a Null-coalescing operator #1949
Comments
👍 for this feature. |
👍 |
👍 do it |
👍 |
I'm having trouble writing a test for an operation that includes a named expression: I can't figure out how to get Could somebody lend me a hand, please? (working implementaiton: michaelrog@9af84d4) |
This is something that would definitely clean up our templates. 👍 |
@michaelrog Can you submit a PR? We can then help you there, much easier than commenting on a moving target. |
See #1972 for a tested implementation |
@fabpot Very nice! Thanks, and sorry I wasn't quite quick enough in following up on this. |
This is awesome, thanks! Don't suppose there could be any equivalent for testing against |
@andregoldstein Twig supports the short ternary operator of PHP too ( |
Many thanks, didn't know about |
I frequently find myself needing to use null-coalescing in my Twig templates (i.e. given several variables, use the first one that is set and not null).
The ternary operators and
default
filter are sometimes useful, but both have the downside of becoming unmanageably verbose when there are more than one or two possible variables in play.For example:
thing1|default(thing2|default(thing3|default(thing4|default('Oy vey.'))))
or worse...
(thing1 is defined and thing1 is not null ? thing1 : (thing2 is defined and thing2 is not null ? thing2 : (thing3 is defined and thing3 is not null ? thing3 : ('This is ridiculous.') ) ) )
It's in Twig's raison d'etre to be "Concise"... so why not:
thing1 ?? thing2 ?? thing3 ?? thing4 ?? 'Nice.'
PHP offers a null-coalescing operator natively as of version 7, but it is straightforward to implement a shim for earlier versions.
I added a proof-of-concept in a CraftCMS plugin, here: https://bitbucket.org/topshelfcraft/null-coalescing-twig-operator/src/5f86e32aa53d6a49f26ebc36926c404bd145221b/qq/twigoperators/QqNullCoalesce.php
I would like to clean up my POC, combine the shim and native versions into a single class, and contribute it to Twig core. Would this be a welcome addition?
The text was updated successfully, but these errors were encountered: