1

In my custom modules I am creating a custom content type. I also need to apply a twig template for this custom content type, but I can't seem to get it to actually apply.

in myModule.module file I have:

function myModule_theme($existing, $type, $theme, $path) {


return [
    'faculty_bio_node' => [
      'variables' => [],
    ]
  ];
}

and I have a custom twig template named : faculty_bio-node.html.twig

The content types machine name is faculty_bio

7
  • 1
    You don't need a theme hook to be able to use a custom template for a content type. That's built in to Drupal's theming already. Name your template node--faculty-bio.html.twig for example. drupal.org/docs/8/theming/twig/twig-template-naming-conventions Aug 9, 2018 at 14:11
  • I have the twig template inside a templates folder, and the naming convention you shared did not work (with a cache clear of course) Any idea what I'm doing wrong?
    – RJ Reedy
    Aug 9, 2018 at 14:17
  • If the template is in your module folder rather than the theme, then yes, that won't work. You'll need to implement the hook api.drupal.org/api/drupal/… I think, though there may be other ways to override the location of a template. Aug 9, 2018 at 14:28
  • 1
    If you want to load the template from the module folder you are in the right hook, but you need to use the correct base hook. This means you have to start the template name with the base hook and a double underscore node__ and declare the base hook in theme_hook(), see drupal.stackexchange.com/questions/194498/…
    – 4uk4
    Aug 9, 2018 at 18:43
  • 1
    AHA! That did it for me! Thank you @4k4 If you want to put that in as an answer I'll happily accept it~!
    – RJ Reedy
    Aug 9, 2018 at 19:34

2 Answers 2

4

If you want to load the template from the module folder you are in the right hook, but you need to use the correct base hook. This means you have to start the template name with the base hook and a double underscore node__ and declare the base hook in theme_hook(), see Store template in module.

hook_theme():

function myModule_theme($existing, $type, $theme, $path) {


return [
    'node__faculty_bio' => [
      'base hook' => 'node',
    ]
  ];
}

The Twig template path and name would then be mymodule/templates/node--faculty-bio.html.twig.

1
  • been strugling with this for hours, awesome man thans
    – uneeb meer
    Feb 15, 2021 at 17:17
0

Drupal won't recognize the template using an underscore. Rather than using: faculty_bio-node.html.twig Can you try faculty-bio-node.html.twig

Using this you can leave the return method for what it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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