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
![Jazi](https://i.stack.imgur.com/HAGLf.png?s=256&g=1)
Author by
Jazi
Updated on August 17, 2022Comments
-
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 about 8 yearsIf it needs to be an int, why aren't you verifying that before handing it to the view?
-
Jazi about 8 yearsThe point is that It's not always an int. That's why I must do it like that.
-
Jonnix about 8 yearsThat makes more sense :)
-
Yoshi about 8 yearsWouldn't it be better to just add a new test? It keeps your templates readable and is reusable.
-
Jazi about 8 years@Yoshi Could be. I'm just a beginner in Twig for now :/.
-
-
Tomas Votruba almost 5 yearsThank you, nice and easy simple solution <3
-
colonelclick over 3 yearsThis 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