isset() 和 !empty() 的 Twig 等价物是什么?

2022-01-22 00:00:00 php twig

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

推荐答案

参见 Tests 用于所有测试.要使用测试,请使用 variable is test.您在空"测试中缺少是".感谢@DarkBee 指出了这个小错误.

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.

但要回答您最初的问题,请查看 Twig/Extension/Core.php.该类显示了每个 Twig 测试在后台"是如何工作的.

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

这是一个包含所有测试及其 PHP 等效项的小表格:

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 检查:

  • 如果是数组:count(array) === 0
  • 如果是对象:Object::__toString === ''
  • 如果是其他内容(例如字符串、浮点数或整数):'' === $value ||错误 === $价值 ||空 === $值 ||array() === $value

相关文章