'Print user role when submitting comments in Drupal 8

In my Drupal site, user profile has username, role and group Taxonomy term. There is a Article content type setup to take comments from users. Every time when a user comments, I would like to show as:

Submitted by: username, role, group

I tried to read the role and category fields through template_preprocess function as below:

function bartik_preprocess_comment(array &$variables) {
  if (isset($variables['elements']['#view_mode'])) {
    $variables['view_mode'] = $variables['elements']['#view_mode'];
  }
  else {
    $variables['view_mode'] = 'default';
  }
  dd($variables);
}

But the dump does not show "group" field. Unsure what's missing.Rightnow, only the username is showing up. My comments.html.twig looks as below:

  <div class="author-comments">
      <p class="comment-submitted">{{ submitted }}</p>
      <div{{ content_attributes.addClass('content') }}>
        {% if title %}
          {{ title_prefix }}
          <h3{{ title_attributes }}>{{ title }}</h3>
          {{ title_suffix }}
        {% endif %}
        {{ content }}
      </div>
    </div>

any help on how to pull out the role and category field and plug into the twig template? Thanks!



Solution 1:[1]

Alright, I'm able to figure this out. Below is my answer:

In mytheme.theme file:

/**
 * Implements hook_preprocess_HOOK() for comment.html.twig.
 */
function mytheme_preprocess_comment(array &$variables) {
  $user = \Drupal::currentUser();
  $user_entity = \Drupal::entityTypeManager()
                ->getStorage('user')
                ->load($user->id());

  $roles = $user->getRoles();
  $variables['user_roles'] = $roles ;
}

This variable can be printed on comment.html.twig as: {{ user_roles }} as however needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rick