Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig string render and Symfony extensions

Tags:

twig

symfony

I'm using twig in my Symfony2 project to render templates form variable:

$env = new \Twig_Environment(new \Twig_Loader_String());
$render = $env->render(
    $renderString,
    $params
);

But when I trying to use Symfony twig functions(such as 'path', 'url', 'asset', 'controller', etc) it throws exception "The function "path" does not exist in...". There is the way to inject this function to the Twig_Environment?

like image 936
Phantaminuum Avatar asked Apr 24 '14 11:04

Phantaminuum


2 Answers

This method works without cloning the twig environment: (Tested in symfony 3)

$rendered = $this->get('twig')
    ->createTemplate('Hi {{ name }}!')
    ->render(['name' => 'simon']);

Symfony extensions like path work, like requested.

like image 163
Simon Epskamp Avatar answered Sep 22 '22 13:09

Simon Epskamp


Try this :

$twig = clone $this->get('twig');
$twig->setLoader(new \Twig_Loader_String());
$rendered = $twig->render(
    "Test string template: {{ result|humanize }}",
    array("result" => "mega_success")
);

cf. How to render a string as a Twig template in Symfony2

like image 26
TaKe_Da_ShAkEr Avatar answered Sep 18 '22 13:09

TaKe_Da_ShAkEr