2016-08-25 7 views
0

Я использую силикатного (1.3) для проекта, и я хотел бы добавить расширение Twig, который соответствует интерфейсу Twig_Extension:Добавление класса 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". 

Но нет никаких проблем в моем Еогеаспе, потому что если я бэры ove мое расширение Twig, шаблон загружается без каких-либо ошибок.

Добавление фильтров и функций в файл начальной загрузки действительно раздражает меня.

Любая помощь будет оценена!

ответ

1

Решение довольно простое. Вы забыли вернуть свой массив фильтров, скорректируйте свой код на:

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

У вас есть острый глаз, я прочитал его. – Xorifelse

+0

Спасибо @DarkBee, но это не решение. Решение было: 'return array (new \ Twig_SimpleFilter ('relative', array ($ this, 'relative'))); '. Я оставляю записку про себя: внимательно прочитайте документацию. – JoHTVS

 Смежные вопросы

  • Нет связанных вопросов^_^