Drupal 8: Theme / Template suggestions for user view modes

Just a quick note to mysqlf: Drupal 8 Core provides several theme or template suggestions for the node entity type, but not for the user entity type. So if you want different templates or theme functions for your user view modes, implement hook_theme_suggestions_HOOK().


/**
 * Implements hook_theme_suggestions_HOOK()
 */
function mymodule_theme_suggestions_user(array $vars) {
  $suggestions = [];
  $user = $vars['elements']['#user'];
  $sanitized_view_mode = strtr($vars['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'user__' . $sanitized_view_mode;
  $suggestions[] = 'user__' . $user->id();
  $suggestions[] = 'user__' . $user->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}