What is the Twig equivalent of the below PHP ternary condition?
<?php echo (isset($myVar) && !empty($myVar)) ? $myVar : '#button-cart'; ?>
I have ingloriously tried this but it doesn't look good and of course, it doesn't work:
{{ myVar is defined and myVar not empty ? myVar : '#button-cart' }}
Support for the __toString() magic method has been added in Twig 2.3. empty checks if a variable is an empty string, an empty array, an empty hash, exactly false , or exactly null . For objects that implement the Countable interface, empty will check the return value of the count() method.
The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not. The isset() function will generate a warning or e-notice when the variable does not exists. The empty() function will not generate any warning or e-notice when the variable does not exists.
isset() returns false only when the variable exists and is not set to null , so if you use it you'll get true for empty strings ( '' ).
See Tests for all tests. To use a test, use variable is test
. You're missing 'is' in your 'empty' test. Credits to @DarkBee for pointing out that little mistake.
But to answer your initial question, take a look at Twig/Extension/Core.php.That class shows how every Twig test works 'under the hood'.
Here is a small table with all tests and their PHP equivalent:
| Twig test | PHP method used |
|--------------|---------------------------------------------------|
| constant | constant |
| defined | defined |
| divisible by | % |
| empty | twig_test_empty |
| even | % 2 == 0 |
| iterable | $value instanceof Traversable || is_array($value) |
| null | null === |
| odd | % 2 == 1 |
| same as | === |
twig_test_empty
checks:
count(array) === 0
orObject::__toString === ''
or'' === $value || false === $value || null === $value || array() === $value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With