Get Username from UID with Preprocess for Template
It's better to use the route instead of the path, where you'll find the already loaded user entity:

if (\Drupal::routeMatch()-&gt;getRouteName() == 'entity.user.canonical') {
  $user = \Drupal::routeMatch()-&gt;getParameter('user');
  $username = $user-&gt;getUsername();
}