5

Is there a way i can create a diffrent template than user.html.twig to have a diffrent View mode when i use default, compact or user account

Something like user--compact.html.twig ?

13

You can do this by creating a theme suggestion alter hook in your theme.

/**
 * Implements hook_theme_suggestions_user_alter().
 *
 *   An array of alternate, more specific names for template files or theme
 *   functions.
 */
function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) {

  // Define the view mode.
  $mode = $vars['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;
}

Note, $vars['elements']['#view_mode']; was derived from using kint($vars) under this function to see the view mode array in user.

You can add this code to your theme's .theme file and then clear cache. Once you clear cache, you will then see the new theme suggestions appear within Twig debug.

Note, in my case, I am in "full view mode so that's why user--full.html.twig shows up. If you are view the user in compact mode, then a suggestion of user--compact.html.twig will show up.

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.