Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
Test existence of a macro in Twig 2

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,

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

See this example live

Another approach would be to create a custom test to do the job.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!