I used hook_theme_suggestions_HOOK_alter:

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;
}

Now I can work with user--full.html.twig and user--compact.html.twig

But I have a role editor and I want to user--compact--editor.html.twig to be picked up. How can I add a template suggestion based on user roles?

up vote 3 down vote accepted

All you need to do is to get the current user object, get its roles, and then add the suggestion like in the following snippet. The current user also already is available in the $variables.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {

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

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

  // Get current user.
  $current_user = $variables['elements']['#user'];

  // Get current user's roles.
  $roles = $current_user->getRoles();

  // Add suggestion per role.
  foreach ($roles as $role) {
    $suggestions[] = 'user__' . $mode . '__' . $role;
  }
}

This will give you:

<!-- FILE NAME SUGGESTIONS:
   * user--full--administrator.html.twig
   * user--full--authenticated.html.twig
   * user--full.html.twig
   x user.html.twig
-->

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.