<?php
// creating a hash twig function as Extension
class MyTwigFunctions extends Twig\Extension\AbstractExtension
{
public function getName()
{
return 'MyFunctions';
}
public function getFunctions()
{
return [
new Twig\TwigFunction('hash', [$this, 'myHash']),
];
}
public function myHash($value)
{
return hash('crc32', $value);
}
}
$path = __DIR__ . '/templates/';
$file = 'hash.html.twig';
echo '- template content:' . PHP_EOL;
echo file_get_contents($path . $file) . PHP_EOL;
$loader = new Twig\Loader\FilesystemLoader($path);
$twig = new Twig\Environment($loader);
$twig->addExtension(new MyTwigFunctions());
echo '- rendered template:' . PHP_EOL;
echo $twig->render($file);