'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.
Solution 1:[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:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 |