문제

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?

도움이 되었습니까?

해결책 2

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top