5

I'm working on a Drupal 8 project and in my module X twig template I need to include the template of an other module Y. All what I found in documentation is how to call a template inside other template in theme see here

I've tried in my twig-of-module-X.html.twig file:

{% include 'modules/Y/templates/twig-of-module-Y.html.twig' %}

but doesn't work! Any suggestion please?

1 Answer 1

13

Include the template file with its namespace:

{% include '@modulename/template_file.html.twig' %}

{# @modulename refers to 'path_to_module/templates' #}

Drupal provides a @namespace for Twig based on the machine name of every module and every theme. The @namespace points to the templates sub-directory of that module or theme.

8
  • Thanks bro! please update your answer use {% %} instead of {{ }}
    – MiharbKH
    Sep 25, 2018 at 9:40
  • And also @modulename refers to path_to_module/templates so some_subdir means templates directory sub_dirs it works for me thanks :)
    – MiharbKH
    Sep 25, 2018 at 9:41
  • should not use templates in path it's included in twig namespace (@modulename) {% include '@modulename/if_a_subdir_exist_in_templates_directory/template_file.html.twig' %}
    – MiharbKH
    Sep 25, 2018 at 10:30
  • 2
    Edited once again, hope it is correct now
    – Hudri
    Sep 25, 2018 at 10:44
  • 1
    @dibs Yeah! you could do it using with keyword. example: {% include '@modulename/template-file.html.twig' with {'var1': 'Hello world'} %} And in template-file.html.twig: <h1>{{ var1 }}</h1>
    – MiharbKH
    Oct 4, 2022 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.