isset() 和 !empty() 的 Twig 等价物是什么? [英] What is the Twig equivalent of isset() and !empty()?

查看:18
本文介绍了isset() 和 !empty() 的 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

这篇关于isset() 和 !empty() 的 Twig 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆