Score:0

How can I load a template from a custom module on a certain page?

cn flag

I have a page at path /user/{id}/module, and I'm trying to have Drupal load a custom template from my module when this page is accessed.

The twig debug output shows suggestions for the template name like below, but it doesn't seem to pick the template up even after cache rebuilds. The page needs to show for all users so cannot pin it to a specific id, but html--user--module.html.twig is not respected.

<!-- FILE NAME SUGGESTIONS:
   * html--user--module.html.twig
   * html--user--123456.html.twig
   * html--user--%.html.twig
   * html--user.html.twig
   x html.html.twig
-->

Is there some syntax I've not been able to find like html--user--wildcard-id--module.html.twig?

sonfd avatar
in flag
You have to do special stuff for Drupal to look in your module's directory for a template override. By default it only looks to the active theme.
leymannx avatar
ne flag
Does this answer your question? [Override theme template from module without implementing a theme](https://drupal.stackexchange.com/questions/200602/override-theme-template-from-module-without-implementing-a-theme)
cn flag
@leymannx thanks for that. It's the same solution but different way to encounter the issue, I have both a custom theme and module. I voted for Sam's answer on this question but don't have the rep to mark it accepted.
Score:0
es flag
Sam

Use template from a module

You have to specify the template in hook_theme() with the correct base hook.

Here is example for hook 'node':

function MY_MODULE_theme($existing, $type, $theme, $path) {
  return [
    'node__custom-type__full' => [
      'template' => 'node--custom-type--full',
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'MY_MODULE') . '/templates/content', // if custom
    ],
  ];
}

Other solution : create new suggestion

You can do this in theme_suggestions_alter()

Check theme_suggestion_alter

Here is a example, this is a solution to create template suggestion for form with id form :

function MY_THEME_theme_suggestions_alter($existing, $type, $theme, $path) {
  if ($hook === 'form' && !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

(Create for me the form--user-login-form.html.twig)

In you case, replace $hook by html and add id user

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.