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

2020-08-18 05:53发布

问题:

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

回答1:

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


标签: php twig