How to add twig template suggestions per display mode with custom module? I have a custom module where I am trying to use custom twig templates based on the user view mode. The templates files I am trying to add to my theme are:


user.html.twig
user--compact.html.twig
user--token.html.twig


These reside in a folder called MYMODULE/templates/.

This is my current module code:

module_name.module:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user' =&gt; [
      'template'  =&gt; 'user',
      'base hook' =&gt; 'user',
    ],
    'user__compact' =&gt; [
      'template'  =&gt; 'user--compact',
      'base hook' =&gt; 'user',
    ],
    'user__token' =&gt; [
      'template'  =&gt; 'user--token',
      'base hook' =&gt; 'user',
    ],
  ];

}
The fix was ensuring to add the theme suggestions via HOOK_theme_suggestions_HOOK_alter(), as well as switching one template from user to user__full. Below is the updated module code:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_user_alter(&amp;$suggestions, $variables) {

  $view_mode = $variables['elements']['#view_mode'];
  $suggestions[] = 'user__' . $view_mode;
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user__full'    =&gt; [
      'template'  =&gt; 'user--full',
      'base hook' =&gt; 'user',
    ],
    'user__compact' =&gt; [
      'template'  =&gt; 'user--compact',
      'base hook' =&gt; 'user',
    ],
    'user__token'   =&gt; [
      'template'  =&gt; 'user--token',
      'base hook' =&gt; 'user',
    ],
  ];
}