Skip to content
Advertisement

Is it possible to make global macros in Twig 3?

I want to upgrade my Twig from very old version (2.x or even 1.x) to 3.3. In old version macros imported in top level template are available in all extened and included templates. And I have a bunch of templates where I need my macros (100+ and many embed blocks). I don’t want to import macros manually in evety template.

So, according to similar question Twig auto import macros by environment I tried to implement suggested solution, but it doesn’t work. Actually I tried this:

JavaScript

I also tried this:

JavaScript

but I have same result. In templates fnc is defined but it’s a Template object and I can not access macros. I get a fatal error when I try to do it:

JavaScript

As I understand, in Twig 3 you can not just include macros using addGlobal.

Old Twig was added to our repository (was not ignored) and we probably will add to repository new Twig too, so it’s possible to modify Twig’s source code.

UPD: When I try just to addGlobal my template with macros I get

JavaScript

I’ve solved this problem using this solution (I’ve extended Environment class).

Advertisement

Answer

During some testing I found out you can still call the “functions” defined inside a macro with pure PHP

JavaScript

With this in place you could write a wrapper around the macro and try to auto load them in a container.


First off we need an extension to enable and access the container

JavaScript

Next the container itself. The container is responsible to load and store/save the (auto loaded) macros in the memory. The code will try to locate and load any file in the map macros in your view folder.

JavaScript
JavaScript

Last off we need to mimic the behavior I’ve posted in the beginning of the question. So lets create a wrapper around the macro template which will be responsible to call the actual functions inside the macro.

As seen the functions inside a macro get prefixed with macro_, so just let auto-prefix every call made to the macro wrapper with macro_

JavaScript

Now inject the extension into twig

JavaScript

This will enable the function macro inside every template, which lets us access any macro file inside the macros folder

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement