如何检查变量是否为数字、整数或浮点数?我找不到相关信息。在Symfony 3中制作项目。
最后找到了一些东西。其中一个答案来自:https://craftcms.stackexchange.com/questions/932/how-to-check-variable-type
{# Match integer #}
{% if var matches '/^\\d+$/' %}
{% endif %}
{# Match floating point number #}
{% if var matches '/^[-+]?[0-9]*\\.?[0-9]+$/' %}
{% endif %}
{% 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