Display Themed 'username' in Block I am trying to display the themed username in a custom block.

MyCustomBlock.php:

public function build() {

  $usersData = \Drupal::service('user.data')-&gt;get('my_module');

  $usersFromQuery = [];

  foreach ($usersData as $id =&gt; $value) {
    if (some logic) {
      $usersFromQuery[] = User::load($id);
    }
  }

  $userList = \Drupal::entityTypeManager()
    -&gt;getViewBuilder('user')
    -&gt;viewMultiple($usersFromQuery, 'compact');

  return $userList;

}


This gets me all the users I need, but not the altered/themed username I need.

In MYMODULE.module I am altering the username.

I've also tried:


$users = User::loadMultiple($userQuery);
User::load($uid)-&gt;getDisplayName()


but the username is rendered without hook_preprocess_username() alters.

I think the issue is similar to needing this: https://drupal.stackexchange.com/a/278717/79805

$variables['userName'] = [
  '#theme' =&gt; 'username',
  '#account' =&gt; $account,
];


but I am unsure how to get the themed username in my block.

How can I display the altered username in my block?



Update:

Using a helper function in MYMODULE.module that creates the markup for the altered username, and -&gt;setUsername(), I am able to change the username in my custom block.

foreach ($usersData as $id =&gt; $value) {
  if (some logic) {
    $userItem = User::load($id);
    $userItem-&gt;setUsername(markup($id, $userItem-&gt;getUsername()));
    $usersFromQuery[] = $userItem;
  }
}


But is not really an answer to the question.
You invoke hook_preprocess_username() by rendering the template username. Since D8 has no longer a theme() function the only way to do this is by putting the template in #theme of a render array. In your case multiple times:

public function build() {
  $build = [];
  foreach ($usersFromQuery as $user) {
    $build[] = [
      '#theme' =&gt; 'username',
      '#account' =&gt; $user,
    ];
  }
  return $build;
}