2016-11-21 62 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),]); 
    } 
}