Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 740
Jazi Avatar asked Apr 27 '16 16:04

Jazi


2 Answers

At last found something. One of the answers from: 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 %}
like image 129
Jazi Avatar answered Nov 10 '22 03:11

Jazi


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

With that, you'll be able to write :

{% if foo is numeric %}...{% endif %}

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://symfony.com/doc/current/templating/twig_extension.html

like image 42
Pierre-Olivier Vares Avatar answered Nov 10 '22 03:11

Pierre-Olivier Vares