Reputation: 554
I'm using Silex (1.3) for a project and I wanted to add a Twig extension that complies with the Twig_Extension interface :
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';
}
}
After adding it :
$app["twig"] = $app->share($app->extend("twig", function (\Twig_Environment $twig, Silex\Application $app) {
$twig->addExtension(new LizardCMS\Twig\Extension\DateExtension());
return $twig;
}));
...this cute error appears :
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".
But there's no problem in my foreach because if I remove my Twig extension, the template loads without any error.
Adding filters and functions in the bootstrap file is really annoying to me.
Any help would be appreciated!
Upvotes: 0
Views: 284
Reputation: 15624
The solution is quite simple. You forgot to return your array of filters, adjust your code to :
public function getFilters() {
return array(new \Twig_SimpleFilter($this, 'relative'));
}
Upvotes: 1