添加 Twig Extension class 会导致编译错误

Adding a Twig Extension class makes compilation errors

我正在为一个项目使用 Silex (1.3),我想添加一个符合 Twig_Extension 接口的 Twig 扩展:

namespace LizardCMS\Twig\Extension;

class DateExtension extends Twig_Extension {

public function getFilters() {
    array(new \Twig_SimpleFilter($this, 'relative'));
}

public function relative($date) {
    $date = new \DateTime($date);
    $difference = time() - $date->getTimestamp();
    $periods = array("seconde", "minute", "heure", "jour", "semaine", "mois", "an", "decade");
    $lengths = array("60", "60", "24", "7", "4.35", "12", "10");

    for ($j = 0; $difference >= $lengths[$j] and $j < 7; $j++)
        $difference /= $lengths[$j];
        $difference = round($difference);
        if ($difference != 1) {
            $periods[$j].= "s";
    }
    $text = "il y $difference $periods[$j]";
    return $text;
}

public function timestamp($date) {
    $datetime = new \DateTime($date);
    return "il y a ".$datetime->getTimestamp()." secondes";
}

public function daymonthyear($date, $withSlashes = true) {
    $datetime = new \DateTime($date);
    $separator = ($withSlashes ? "/" : "-");
    return "le ".$datetime->format("d".$separator."m".$separator."Y");
}

public function chosenDateTimeFormat($app, $date) {
    $format = strtolower($app['controller.configuration']->findAll()->getDateTimeFormat()); 
    if(in_array($format, array("relative", "timestamp", "daymonthyear"))) {
        return $this->$format($date);
    } 
}

public function getName() {
    return 'Date';    
}

}

添加后:

  $app["twig"] = $app->share($app->extend("twig", function (\Twig_Environment $twig, Silex\Application $app) {
$twig->addExtension(new LizardCMS\Twig\Extension\DateExtension());
return $twig;
}));

...出现这个可爱的错误:

Twig_Error_Syntax in Environment.php line 601: An exception has been thrown during the compilation of a template ("Warning: Invalid argument supplied for foreach()") in "index.html.twig".

但是我的 foreach 没有问题,因为如果我删除我的 Twig 扩展,模板加载没有任何错误。

在 bootstrap 文件中添加过滤器和函数对我来说真的很烦人。

如有任何帮助,我们将不胜感激!

解决方法很简单。您忘记了 return 您的过滤器数组,请将您的代码调整为:

public function getFilters() {
   return array(new \Twig_SimpleFilter($this, 'relative'));
}