添加自定义过滤器功能

以下是如何向 twig 添加新过滤器/功能的示例,添加 Twig_Functions 的 synax 与 Twig_Filter 相同,只需相应更改关键字

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