2

I'm trying to get my user role thanks to a function in my theme.theme file.

function theme_get_user_role(){
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
}

then in my view :

{% set roles = theme_get_user_role() %}
{{ dump(roles) }}

But I have this error :

Twig_Error_Syntax : Unknown "theme_get_user_role" function. dans Twig_ExpressionParser->getFunctionNodeClass()

What do I miss ?

4
  • 1
    A lot. Well, that's not the way how you would pass something into your template. You'd rather need to use a preprocess function.
    – leymannx
    Aug 27, 2018 at 8:43
  • I've also tried this (theme_template_preprocess_user) but nothing else append if I override the function Aug 27, 2018 at 8:46
  • Yes, as you don't want to preprocess the user. You want to preprocess a view (at least that's what it sound like, correct me if wrong). So it probably would be something like theme_preprocess_views_view(&$variables) where you'd do your logic and then add the output to $variables['foo'] = 'bar' and in the corresponding template then access it via {{ bar }}.
    – leymannx
    Aug 27, 2018 at 8:50
  • I've added this theme_template_preprocess_views_view(&$variables) into theme.theme, but this is returning null (I tried to display "title", also returning null) Aug 27, 2018 at 9:26

1 Answer 1

11

You can use below without any function. Because the User module provides the variable in preprocess for all templates: :

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

If you want to do anything only for the particular role then do this:

{% if 'ROLENAME' in user.getroles(TRUE)  %}
  <p>The user has the role "ABC".</p>
{% endif %}
10
  • already tried. This is giving me the list off all roles, I need current user role :) Aug 27, 2018 at 8:48
  • If you want to exclude "authenticated" role you have to write some logic to get that. Drupal by default will provide "authenticated" role for all users. Updated answer to get current role.
    – Ajay Reddy
    Aug 27, 2018 at 8:50
  • I just need to get roles from my current user, I've added some roles and I want to show them, no matter if it's authenticated or not Aug 27, 2018 at 9:23
  • What are the roles that your current user have? Can you list down here? If you want to get all roles user user.getroles() and if you want to get all roles excluding of authenticated role use user.getroles(TRUE)
    – Ajay Reddy
    Aug 27, 2018 at 9:24
  • Commercial and Director Aug 27, 2018 at 9:25

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.