What is the Twig equivalent of isset() and !empty()?(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 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:isset() 和 !empty() 的 Twig 等价物是什么?


基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01