4

I created a module that contains a large number of custom templates. They are only used for the module's output; they don't override any existing template file.

I would like to place these templates in sub-directories inside the templates directory.

If I place a template in a sub-directory and set a block's #theme to 'account/list_block', for example, the block isn't rendered, but I don't get errors.

When I keep the template in the sub-directory but set #theme to 'list_block', I get the following error.

Template "modules/contrib/mymodule/templates/list-block.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/contrib/mymodule/templates/list-block.html.twig" in the Drupal theme registry.).

From the first example, it seems that Drupal knows the template exists and where to find it, but it doesn't render it.

Is using sub-directories in the "templates" directory possible?

2
  • Not just possible, should be very easy :) What does your hook_theme() implementation look like? You just need to set the template key there to whatever makes sense (e.g. 'account/list_block')
    – Clive
    Commented Mar 22, 2016 at 16:13
  • Nice, I would guess they haven't done away with hooks completely because they need advanced logic sometimes and yaml doesn't really give you that. But yeah, I was a bit surprised when I saw D8 that everything hadn't been moved to subscribed events. Maybe that's too clunky, who knows
    – Clive
    Commented Mar 22, 2016 at 18:02

1 Answer 1

5

You just need to specify the path to the template in hook_theme(), eg

function MYMODULE_theme() {
  return [
    'list_block' => [
      'variables' => [],
      // Underscores are not converted to dashes automatically in this case.
      'template' => 'account/list-block',
    ],
  ];
}

Your Answer

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