Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda