2016-08-25 41 views
0

我使用的Silex(1.3)的一個項目編譯錯誤,我想補充一點,與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,因爲如果我REM在我的Twig擴展中,模板加載沒有任何錯誤。

在引導文件中添加過濾器和函數對我來說真的很煩人。

任何幫助,將不勝感激!

回答

1

該解決方案非常簡單。您忘記返回您的過濾器陣列,請將您的代碼調整爲:

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

您有一顆敏銳的眼睛,我讀過它。 – Xorifelse

+0

謝謝@DarkBee,但它不是解決方案。解決方法是:'返回數組(新\ Twig_SimpleFilter('相對',數組($ this,'相對'))); '。我給自己留個便條:仔細閱讀文件。 – JoHTVS