Is it possible to check if given variable is string in Twig
?
Expected solution:
messages.en.yml
:
hello:
stranger
There is no way to check it correctly using code from the box.
It's better to create custom TwigExtension
and add custom check (or use code from OptionResolver
).
So, as the result, for Twig 3
, it will be smth like this
class CoreExtension extends AbstractExtension
{
public function getTests(): array
{
return [
new TwigTest('instanceof', [$this, 'instanceof']),
];
}
public function instanceof($value, string $type): bool
{
return ('null' === $type && null === $value)
|| (\function_exists($func = 'is_'.$type) && $func($value))
|| $value instanceof $type;
}
}