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') ? 'β
' : 'β' }}
HTML demo of the snippet
Variables
*
* @return array<string,mixed>
*/
public function data58(array $data): array
{
return $this->activateAnsi($data);
}
/**
* @see templates/snippet/code/_72_demo.html.twig
*
* @param array<string,mixed> $data
*
* @return array<string,mixed>
*/
public function data72(array $data): array
{
$data['form'] = $this->formFactory->create(CustomRenderingType::class)->createView();
β¬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 | β | β | β | β | β | β | β | β | β |
<?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'])];
}
/**
* @param mixed $var
*/
public function ofType($var, string $test, string $class = null): bool
{
switch ($test) {
case 'array':
return is_array($var);
case 'bool':
return is_bool($var);
case 'object':
return is_object($var);
case 'class':
return is_object($var) === true && $class === get_class($var);
case 'float':
return is_float($var);
case 'int':
return is_int($var);
case 'numeric':
return is_numeric($var);
case 'scalar':
return is_scalar($var);
case 'string':
return is_string($var);
default:
throw new \InvalidArgumentException(sprintf('Invalid "%s" type test.', $test));
}
}
}
More on Stackoverflow More on the web Random snippet