2016-11-21 102 views
2

枝條函數返回枝條模板可能嗎?枝條函數返回一個模板

例如

class ToTimeExtension extends \Twig_Extension { 

    public function getFunctions() { 
     return array(
      'totime' => new \Twig_Function_Method($this, 'toTime') 
     ); 
    } 

    public function toTime ($string) { 
     $time = strtotime($string); 
     return {"time.html.twig", $time}; 
     //return a twig template and pass $time variable 
    } 

} 

time.html.twig

<h1>{{time}}</h1> 

使用

{{ totime('now') }} 
+0

你真的需要一個函數,爲什麼不只是'{%include'time.html.twig'%}'? –

+0

@RuslanOsmanov這只是一個例子。在後端運行更復雜的邏輯。 –

回答

4

如果你設置了正確的選項,您可以訪問Twig環境。然後你可以在方法內渲染另一個模板。

class ToTimeExtension extends \Twig_Extension { 
    public function getFunctions() { 
     return array(
      'totime' => new \Twig_Function_Method($this, 'toTime', ['needs_environment' => true,]) 
     ); 
    } 

    public function toTime (Twig_Environment $twig, $string) { 
     return $twig->render('time.html.twig', [ 'time' => strtotime($string),]); 
    } 
}