<?php
// creating a twig filter Extension
class MyTwigFilters extends Twig\Extension\AbstractExtension
{
public function getName()
{
return 'MyFilters';
}
public function getFilters()
{
return [
new Twig\TwigFilter('to_int', [$this, 'toInt']),
];
}
public function toInt($value)
{
return (int) $value;
}
}
$templates = [
'filter-template' => 'Filtered value: {{ null|to_int }}',
];
echo '- template content:' . PHP_EOL;
echo $templates['filter-template'] . PHP_EOL;
$loader = new Twig\Loader\ArrayLoader($templates);
$twig = new Twig\Environment($loader);
$twig->addExtension(new MyTwigFilters());
echo '- rendered template:' . PHP_EOL;
echo $twig->render('filter-template');