0

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?

3
  • 3
    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.
    – sonfd
    Jan 14 at 3:02
  • Does this answer your question? Override theme template from module without implementing a theme
    – leymannx
    Jan 14 at 11:49
  • @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.
    – nublet
    Jan 16 at 3:43

1 Answer 1

0

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

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.