It's not much different from how it got solved in the other question you asked. You just have to target page
this time. So hook_theme_suggestions_HOOK_alter()
becomes hook_theme_suggestions_page_alter()
.
And you need to check if you are currently on a user page before you add the suggestion.
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
$route_match = \Drupal::routeMatch();
// Check if on user page.
if ($route_match->getRouteName() == 'entity.user.canonical') {
// Get current user
$current_user = $route_match->getParameter('user');
if ($current_user instanceof \Drupal\user\entity\User) {
// Get user roles.
$roles = $current_user->getRoles();
foreach ($roles as $role) {
// Add template suggestion per role.
$suggestions[] = 'page__user__' . $role;
}
}
}
}
Alternatively, if you want the suggestion to be added only for a certain role, try that:
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
$route_match = \Drupal::routeMatch();
// Check if on user page.
if ($route_match->getRouteName() == 'entity.user.canonical') {
// Get current user
$current_user = $route_match->getParameter('user');
if ($current_user instanceof \Drupal\user\entity\User) {
// Add template suggestion for certain role.
$role = 'somerole';
if ($current_user->hasRole($role)) {
$suggestions[] = 'page__user__' . $role;
}
}
}
}