Using hook_user_format_name_alter(), how to change username on user paths?
This is the title callback you have in core for /user/UID:

UserController::userTitle

/**
   * Route title callback.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   *
   * @return string|array
   *   The user account name as a render array or an empty string if $user is
   *   NULL.
   */
  public function userTitle(UserInterface $user = NULL) {
    return $user ? ['#markup' =&gt; $user-&gt;getUsername(), '#allowed_tags' =&gt; Xss::getHtmlTagList()] : '';
  }


Unfortunately this uses the method getUsername(), which doesn't invoke hook_user_format_name_alter().

You need a custom title callback, where you get the username with the method $user-&gt;getDisplayName(), which does invoke the hook.

Then change the title callback in the user route entity.user.canonical:

$route-&gt;setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::userTitle');


See https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones.



Had the feeling this can't be right and searched for an issue: https://www.drupal.org/node/2648420. This is committed for D8.5. Until then you can apply the patch, which simply replaces getUserName() with getDisplayName() in UserController.