Type cast value objects in twig
When working with value objects, it might make sense to typecast them within a twig template. Out of the box twig doesn't offer typecasting. But it's quite easy to offer it with a custom filter.
Here is an example how the most basic castings would look like:
<?php
declare(strict_types=1);
namespace App\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
final class TypeCastingExtension extends AbstractExtension
{
/** @return array<int, TwigFilter> */
public function getFilters(): array
{
return [
new TwigFilter('int', function ($value) {
return (int) $value;
}),
new TwigFilter('float', function ($value) {
return (float) $value;
}),
new TwigFilter('string', function ($value) {
return (string) $value;
}),
new TwigFilter('bool', function ($value) {
return (bool) $value;
}),
new TwigFilter('array', function (object $value) {
return (array) $value;
}),
new TwigFilter('object', function (array $value) {
return (object) $value;
}),
];
}
}
In a twig template it would be used as any other filter:
Name: {{ user.name | string }}