zelazowy
zelazowy

Reputation: 1056

How to use custom Twig filters in Twig template rendered from string?

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)

Upvotes: 0

Views: 1205

Answers (1)

Luceos
Luceos

Reputation: 6720

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);

Upvotes: 1

Related Questions