Antonio Kovačević Antonio Kovačević - 14 days ago 7
Twig Question

Twig function return a template

Is it possible for a twig function to return a twig template?

For example

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>


Usage

{{ totime('now') }}

Answer

You can access the Twig environment if you set the proper options. Then you can render another template inside the method.

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),]);
    }
}
Comments