2016-11-21 6 views
2

小枝関数が小枝テンプレートを返すことは可能ですか?Twig関数がテンプレートを返す

あなたが適切なオプションを設定する場合は、Twig環境にアクセスすることができます

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

たとえば。次に、メソッド内で別のテンプレートをレンダリングできます。

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),]); 
    } 
} 
関連する問題