'Twig auto import macros by environment

Is it possible (and how) to automatically include specific macro files into every twig file by using PHP (not Twig lang).

Example: I got the file select2 which contains macros to define select2 selections. Now the Twig environment autoincludes every macro in that file under select2.macroname and without calling import in other twig files I can use that macro?

I'm using twig standalone.



Solution 1:[1]

U could inject the file containing the macro's as a global variable into twig

$twig->addGlobal('my_macros', $twig->loadTemplate('macros.html'));

macros.html

{% macro HelloWorld(foo) %}
    {{ foo }}
{% endmacro %}

random_file.html

{{ my_macros.HelloWorld('StackOverflow') }} {# output: StackOverflow #}

UPDATE April 2022

If you are looking for a method to auto-load macros in twig 3.X then have a look at the following answer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1