Twig 函数返回一个模板

Cod*_*ker 3 php symfony twig

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
    }

}
Run Code Online (Sandbox Code Playgroud)

time.html.twig

<h1>{{time}}</h1>
Run Code Online (Sandbox Code Playgroud)

用法

{{ totime('now') }}
Run Code Online (Sandbox Code Playgroud)

Dar*_*Bee 5

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),]);
    }
}
Run Code Online (Sandbox Code Playgroud)