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

36,328

Solution 1

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 %}

Solution 2

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

Share:
36,328
Jazi
Author by

Jazi

Updated on August 17, 2022

Comments

  • Jazi
    Jazi almost 2 years

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

    • Jonnix
      Jonnix about 8 years
      If it needs to be an int, why aren't you verifying that before handing it to the view?
    • Jazi
      Jazi about 8 years
      The point is that It's not always an int. That's why I must do it like that.
    • Jonnix
      Jonnix about 8 years
      That makes more sense :)
    • Yoshi
      Yoshi about 8 years
      Wouldn't it be better to just add a new test? It keeps your templates readable and is reusable.
    • Jazi
      Jazi about 8 years
      @Yoshi Could be. I'm just a beginner in Twig for now :/.
  • Tomas Votruba
    Tomas Votruba almost 5 years
    Thank you, nice and easy simple solution <3
  • colonelclick
    colonelclick over 3 years
    This answer is ok if you need a pure Twig solution, but creating an extension is the recommended method in the documentation for both Twig and Symfony. stackoverflow.com/a/52946699/1440932