Twig - How to check if variable is a number / integer
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 %}
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