I want to know how to show role label in twig view.

I have this

{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

It's giving me my role, but instead of showing "Directeur (CR)", it's showing "directeur_cr_" (the machine name or database value).

How can I display "Directeur (CR)"?

1 Answer 1


You can try like below:

function MYMODULE_field_template_preprocess_default_variables_alter(&$variables) {
  $variables['user_roles'] = user_role_names();

and in .twig file you can use as {{user_roles['ROLE_NAME']}}

  • This is in my theme, is this going to work with changing MYMODULE to theme ? Aug 27, 2018 at 10:27
  • Add this in your .module file anywhere in your custom code. It won't work in the theme file.
    – Ajay Reddy
    Aug 27, 2018 at 10:32
  • How will this give the template the roles the viewed user has?
    – Kevin
    Aug 27, 2018 at 23:41
  • This will nor give roles of the current user. user_roles will all roles with id => label. So, we have to pass the role id in user_roles to get the label.
    – Ajay Reddy
    Aug 28, 2018 at 3:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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