0
votes

I want to render Twig template from string (in fact from database but it doesn't matters) and method showed in this question works fine. But I can't use my custom filters, defined in custom Twig extension, which works in templates rendered in standard way (from files).

What should I do to allow string-templates use custom filters?

I'm getting template from string in this way:

$env = new \Twig_Environment(new \Twig_Loader_String());
echo $env->render(
  "Hello {{ name }}",
  array("name" => "World")
);

I've found in \Twig_Environment class method addFilter but my filters are defined in Twig extension so I don't know if it's proper method to use.

Solution:

Thanks to Luceos comments I've solved my problem just by using existing Twig engine instead of creating new one. When I set Twig Environment this way:

$twig = clone $this->get('twig');
$twig->setLoader(new \Twig_Loader_String());

then everything works as expected. (Solution found in http://www.techpunch.co.uk/development/render-string-twig-template-symfony2)

1
Show your code, how are you parsing the templates? How do you instantiate twig?Luceos
You should re-use the instantiated Twig object from Symfony2, not instantiate one yourself. Doing so will give you a clean Twig environment without all functionality Symfony adds..Luceos

1 Answers

1
votes

Use Symfony's Twig instantiated object and do not set up your own. Setting up your own environment leaves out all added functionality by Symfony.

For instance use the render function in controllers: http://symfony.com/doc/current/book/templating.html#index-8

Or call on the template service directly: http://symfony.com/doc/current/book/templating.html#index-12

use Symfony\Component\HttpFoundation\Response;

$engine = $this->container->get('templating');
$content = $engine->render('AcmeArticleBundle:Article:index.html.twig');

return $response = new Response($content);