簡體   English   中英

Twig函數返回模板

[英]Twig function return a template

樹枝函數是否可以返回樹枝模板?

例如

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') }}

如果設置適當的選項,則可以訪問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),]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM