I would like to have a different user template for each role, but I can't figure it out how do do it.

I've added a preprocess function in my themename.theme like this:

function ras_preprocess_page(&$variables) {

    $variables['role'] = \Drupal::currentUser()->getRoles();

and then used role in my user.html.twig like this:

{% if role == 'administrator' %}
   <p>Hello, admin</p>
{% elseif role == 'anonymous' %}
   <p>Hi, stranger</p>
{% endif %}

But it doesn't work as I would expect.

  • I think getRoles() is returning array, that's why it's not working as expected. – Ziftman May 23 '18 at 10:25
  • Thanks for your comment.Can you please give me a hint on how I can check against and array? – Florin Simion May 23 '18 at 10:28
  • {% if myVar in myArray %} – Ziftman May 23 '18 at 10:30

You can use hook_theme_suggestions_HOOK_alter() like below:

 * Implements hook_theme_suggestions_HOOK_alter().
function THEME_NAME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $roles = \Drupal::currentUser()->getRoles();
  if (in_array('YOUR ROLE',$roles)) {
    $suggestions[] = 'user__'.ROLENAME;

and you have to create


in order to get a specific template for the user based on their role.

| improve this answer | |

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.