上次找到了一些东西。一个答案之一:
{% if foo is numeric %}...{% endif %}
创建您的扩展课:
namespace MyNamespace;
class MyTwigExtension extends \Twig_Extension
{
public function getName()
{
return 'my_twig_extension';
}
public function getTests()
{
return [
new \Twig_Test('numeric', function ($value) { return is_numeric($value); }),
];
}
}
在您的配置中:
services:
my_twig_extension:
autowire: true
class: AppBundle\MyNamespace\MyTwigExtension
tags:
- { name: twig.extension }
请参阅文档:
https://twig.symfony.com/doc/2.x/advanced.html#tests
https://symfony.com/doc/current/templating/twig_extension.html
不能保证这对所有情况都有效,但是在Drupal上下文(Drupal 9/twig 2)中,我可以成功地将一个变量与for循环中的-1进行比较,以区分数字与非数字密钥:{% for i, items %}
{% if i > -1 %}
...