我正在使用Silex(1.3)为一个项目,我想添加一个Twig扩展,符合Twig_Extension接口:
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文件中添加过滤器和函数对我来说真的很烦人。
任何帮助将不胜感激!
解决方案非常简单。您忘记返回过滤器数组,请将代码调整为:
public function getFilters() {
return array(new 'Twig_SimpleFilter($this, 'relative'));
}