php Twig - 如何检查变量是否为数字/整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36895116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:58:42  来源:igfitidea点击:

Twig - How to check if variable is a number / integer

phptypestwigsymfony

提问by Krzysztof Trzos

How to check if variable is a number, integer or float? I can't find anything about this. Making project in Symfony 3.

如何检查变量是数字、整数还是浮点数?我找不到任何关于此的信息。在 Symfony 3 中制作项目。

回答by Krzysztof Trzos

At last found something. One of the answers from: https://craftcms.stackexchange.com/questions/932/how-to-check-variable-type

终于找到东西了。答案之一: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 %}

回答by Pierre-Olivier Vares

You can create a twig extension to add a test "numeric"

您可以创建一个树枝扩展来添加测试“数字”

Create your extension class :

创建您的扩展类:

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); }),
        ];
    }
}

And in your configuration :

在您的配置中:

services:
    my_twig_extension:
        autowire: true
        class: AppBundle\MyNamespace\MyTwigExtension
        tags:
            - { name: twig.extension }

See documentation :

请参阅文档:

https://twig.symfony.com/doc/2.x/advanced.html#tests

https://twig.symfony.com/doc/2.x/advanced.html#tests

https://symfony.com/doc/current/templating/twig_extension.html

https://symfony.com/doc/current/templating/twig_extension.html