Twig函数返回一个模板

时间:2016-11-21 07:23:15

标签: php twig symfony

枝条功能是否可以返回树枝模板?

例如

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

1 个答案:

答案 0 :(得分: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),]);
    }
}