Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

twig

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' }}
like image 571
Carol-Theodor Pelu Avatar asked Nov 22 '17 14:11

Carol-Theodor Pelu


People also ask

Is empty in twig?

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.

What is the difference between empty () and isset () functions?

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.

Does Isset check for empty string?

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 ( '' ).


1 Answers

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
like image 79
Stephan Vierkant Avatar answered Sep 28 '22 03:09

Stephan Vierkant