Twig extension to be available in new Twig_Environ

2019-09-16 18:58发布

问题:

I'm using Symfony 2 / Twig. I have a Twig extension which, among other things, overloads the date filter to output custom date formats based on user preference.

app/config/services.yml:

twig.extension.static:
    class: %twig_static_extension%  # set elsewhere
    tags:
        - { name: twig.extension }

I'm needing to initialize a new Twig_Environment in order to render templates from the database:

controller:

$env = new \Twig_Environment(new \Twig_Loader_String());

But I am finding that this new environment does not automatically include the extension.

Naturally, I can load it like so:

$env->addExtension(new FQCN\To\StaticExtension());

Is there something I can do to make the extension available to all Twig environments that might be used?

回答1:

You can create a Compiler Pass and inject it to your bundle, take a took at TwigEnvironmentPass from TwigBundle



标签: symfony twig