2

I would like to theme user profile pages differently based on the role but I can't figure it out how to do so.

I will need when someone is viewing an administrator profile this twig file to be loaded: user--administrator.html.twig

and when is viewing an editor profile this: user--editor.html.twig

Any idea how can I achieve this?

4

It can done by adding a hook theme suggestion based on roles in your YOUR_THEME.theme file

/**
 * Implements hook_theme_suggestions_user_alter().
 */
function YOUR_THEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  foreach ($variables['elements']['#user']->getRoles() as $role) {
    $suggestions[] = 'user__' . $role;
  }
}

Then you can use templates like user--administrator.html.twig, user--editor.html.twig

  • What this does is to change the template based on the role of the user. So if an editor sees the profile of an administrator they will see the user--editor.html.twig – Florin Simion Jun 20 '18 at 11:50
  • Then you should loop the roles of the currently loaded user in the page $variables['elements']['#user']->getRoles(). I have updated the code. – Razeem Ahmad Jun 20 '18 at 11:58

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.