Testing the type of a variable in a Twig template
Published on 2020-06-15 • Modified on 2020-06-15
In this snippet, we will see how to test the type of a variable in a Twig template. We will create a small extension for this purpose. In the following demo, first, I display the variables that will be used. They are declared in plain PHP, so we are sure of the type. Then I present the test matrix where each variable is tested against each type. To display the test result, I use a ternary expression:
{{ varNumeric is of_type('int') ? 'β
' : 'β' }}
<?php
declare(strict_types=1);
// src/Twig/Extension/TypeExtension.php
namespace App\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigTest;
final class TypeExtension extends AbstractExtension
{
public function getTests(): array
{
return ['of_type' => new TwigTest('of_type', $this->ofType(...))];
}
public function ofType(mixed $var, string $test, ?string $class = null): bool
{
return match ($test) {
'array' => \is_array($var),
'bool' => \is_bool($var),
'object' => \is_object($var),
'class' => \is_object($var) && $class === \get_class($var),
'float' => \is_float($var),
'int' => \is_int($var),
'numeric' => is_numeric($var),
'scalar' => \is_scalar($var),
'string' => \is_string($var),
default => throw new \InvalidArgumentException(\sprintf('Invalid "%s" type test.', $test)),
};
}
}
HTML demo of the snippet
Variables
* This function belongs to the "App\Data\SnippetData" class.
*
* @see templates/snippet/code/_95_demo.html.twig
*
* @param array<string,mixed> $data
*
* @return array<string,mixed>
*/
public function data95(array $data): array
{
$data['types'] = ['array', 'bool', 'object', 'class', 'float', 'int', 'numeric', 'scalar', 'string'];
$data['varArray'] = [4, 5, 6];
$data['varBool'] = true;
$data['varObject'] = $this;
$data['varClass'] = $this;
$data['varFloat'] = 3.14;
$data['varInt'] = 15;
$data['varNumeric'] = '555';
$data['varScalar'] = 'foo';
$data['varString'] = 'bar';
return $data;
}
β¬var is of_type('type') β‘ | array | bool | object | class | float | int | numeric | scalar | string |
---|---|---|---|---|---|---|---|---|---|
varArray | β | β | β | β | β | β | β | β | β |
varBool | β | β | β | β | β | β | β | β | β |
varObject | β | β | β | β | β | β | β | β | β |
varClass (App\Data\SnippetData ) |
β | β | β | β | β | β | β | β | β |
varFloat | β | β | β | β | β | β | β | β | β |
varInt | β | β | β | β | β | β | β | β | β |
varNumeric | β | β | β | β | β | β | β | β | β |
varScalar | β | β | β | β | β | β | β | β | β |
varString | β | β | β | β | β | β | β | β | β |
More on Stackoverflow More on the web Random snippet