twig tutorial - Adding custom filters and functions in Twig - twig php - twig template
Here are some example on how to add new filters/functions to twig,
the synax for adding Twig_Functions are the same as the Twig_Filter ones, just change the keywords accordingly
<?php
$twig = new Twig_Environment($loader);
/* You can chain a global function */
$twig->addFilter(new Twig_SimpleFilter('floor', 'floor'));
/* You can specify a custom function */
$twig->addFilter(new Twig_SimpleFilter('money', function($value, $currency, $prefix = false, $decimals = 2, $dec_point = "." , $thousands_sep = ",") {
$value = number_format($value, $decimals, $dec_point, $thousands_sep);
if ($prefix) return$currency.' '.$value;
return$value.' '.$prefix;
});
/* You can chain an object's method */
$twig->addFilter(new Twig_SimpleFilter('foo_bar', array($foo, 'bar')));