I need to be able to test the existence of a macro in Twig and to call it dynamically.
Here is what I tried:
{% macro test(value) %}
Value: {{ value }}
{% endmacro %}
{% import "_macros.html.twig" as macro %}
{{ attribute(macro, 'test', ['foo']) }}
But I get this error: Accessing Twig_Template attributes is forbidden.
Regards,
Since Twig 1.20.0, template attributes are not available anymore for security reasons, so there are no native way to do it properly.
You can eventually use the source function to get macro's source file and parse it to check if a macro exists, but that's a kind of ugly hack easy to bypass.
Example:
main.twig
{% import 'macros.twig' as macros %}
{% set sourceMacros = source(macros) %}
foo {% if 'foo()' in sourceMacros %} exists {% else %} does not exist {% endif %}
bar {% if 'bar()' in sourceMacros %} exists {% else %} does not exist {% endif %}
macros.twig
{% macro foo() %}
Hello, world!
{% endmacro %}
Another approach would be to create a custom test to do the job.