Carol-Theodor Pelu Carol-Theodor Pelu - 7 months ago 306
Twig Question

What is the Twig equivalent of isset() and !empty()?

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' }}

Answer Source

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:

  • if it's an array: count(array) === 0 or
  • if it's an object: Object::__toString === '' or
  • if it's something else (for example string, float or integer): '' === $value || false === $value || null === $value || array() === $value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download