Check for existence of a macro in Twig 2

I need to be able to check for the existence of a macro in Twig and call it dynamically.

Here's what I've tried:

{% macro test(value) %}
    Value: {{ value }}
{% endmacro %}

{% import "_macros.html.twig" as macro %}

{{ attribute(macro, 'test', ['foo']) }}

      

But I am getting this error: Accessing Twig_Template attributes is forbidden.

Hello,

+3


source to share


1 answer


As of Twig 1.20.0, template attributes are no longer available for security reasons, so there is no native way to do this correctly.

Ultimately you can use a function source

to get the original macro file and parse it to check if the macro exists, but that kind of ugly hack is easy to get around.

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 %}

      

See this example live

Another approach would be to create a custom test to complete the assignment.

+2


source







All Articles