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 4 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
-->
  • Nice. @leymannx would you be willing to be a maintainer of drupal.org/project/twigsuggest and add this? – mlncn Nov 20 at 17:00
  • @mlncn – Yes for the maintainership, as this really seems to be a useful module. About the snippets here, after I dropped that answer I thought to myself: What if a user has multiple roles, and there are multiple templates, how to decide which should be taken into account? Will it take just the first in alphabetical order? Worth some testing. – leymannx Nov 20 at 17:03
  • @lemannx excellent, done, thank you. Oh, yeah, of course, on the multiple roles. I was also thinking if there might be performance issues with getting roles... and now we're in the territory of building a UI for deciding if/which roles to do suggestions for... maybe only if more need is demonstrated! – mlncn Nov 20 at 17:12
  • @mlncn – If roles in the UI are used as intended (with kind of an order from left "anonymous" to right "admin") we maybe only add one suggestion per user for its "highest" role?! Let's discuss this in the module's issue queue. – leymannx Nov 20 at 18:09

Your Answer

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.