How to add author's user role as CSS class to comments? Snippet from Bartik's comment.html.twig ( https://pastebin.com/D70cyHNp ):

{{ user_picture }}
    &lt;p class="comment__author"&gt;{{ author }}&lt;/p&gt;
    &lt;p class="comment__time"&gt;{{ created }}&lt;/p&gt;


I want to highlight comments by administrators with CSS so how can I say "if the comment author has the role administrator, add the class "comment_author_is_administrator" to the author variable?
This can be done pretty easily by preprocessing your comments.

But first of all, very important: don't edit any of Bartik's files (or any core files in general). Create a sub-theme, copy the comment.html.twig to your sub-theme's templates directory and edit that file.

Second, depending on your CSS setup comment_author_is_administrator doesn't seem like a legit CSS class. Normally, underscores are not allowed to be used that way. And maybe you can make it a little bit shorter. Maybe just author-administrator.

Finally, simply place the following snippet in you sub-theme's *.theme file and replace MYTHEME with your actual theme name.

/**
 * Implements template_preprocess_comment.
 */
function MYTHEME_preprocess_comment(&amp;$variables) {

  // Get the comment.
  $comment = $variables['comment'];

  // Get its owner.
  $owner = $comment-&gt;getOwner();

  // Check for administrator role.
  if ($owner-&gt;hasRole('administrator')) {

    // Append CSS class.
    $variables['attributes']['class'][] = 'author-administrator';
  }
}


Alternatively, you could simply append each comment's author role as CSS class like following.

/**
 * Implements template_preprocess_page.
 */
function MYTHEME_preprocess_comment(&amp;$variables) {

  $comment = $variables['comment'];
  $owner = $comment-&gt;getOwner();
  $roles = $owner-&gt;getRoles();

  // Let's pop the roles array to only
  // get the last (highest) role of all.
  $role = array_pop($roles)

  $variables['attributes']['class'][] = 'author-' . $role;
}