Hello,

I created a macro that I want to use (hence import) into a template. I have looked at countless tutorials but none of them seem to help and my macro is not being imported.

This is my folder structure:

-/templates
  -/partials
    header.html.twig
  -/regions
    region--header.html.twig

I would like to import the 'header.html.twig' file (which contains the macro) into 'region--header.html.twig'.

This is the content of the 'header.html.twig' file (which I want to import):

{% macro header(title = "Default Header", color = "white", bgcolor = "blue") %}
    <div style="color: {{ color }}; background-color: {{ bgcolor }};">
        <h1>{{ title }}</div>
    </div>
{% endmacro %}

And I want to import it into the 'region--header.html.twig' file as such:

{% import 'header.html.twig' as header %}

{% if content %}
  <div{{ attributes }}>
    {{ content }}
    {{ header.header('This is my custom header.', 'red', '#338800') }}
  </div>
{% endif %}

I keep getting the error:

Template "header" is not defined in "themes/custom/playground/templates/region/region--header.html.twig".

I tried to place the macro file into the same directory as the region--header.html.twig file is. Same result.

I tried to import the macro as {% import 'partials/header.html.twig' as header %} and also {% import '../partials/header.html.twig' as header %} to import it from the correct directory but all of these is giving the same error as above.

I'd appreciate any help.

Thank you.

Comments

elpea’s picture

I ended up at this post which provided the solution: https://www.drupal.org/project/drupal/issues/2817553

Had to import it by defining the full path like so:

{% import directory ~ '/templates/partials/header.html.twig' as header %}
arturopanetta’s picture

Use

{% import '@theme_name/partials/header.html.twig' as header %}

@theme_name = /themes/theme_name/templates

or

@theme_name = /themes/custom/theme_name/templates

or

@theme_name = /themes/contrib/theme_name/templates

;)