twig Extending twig Adding custom filters/functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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')));


Got any twig Question?