Skip to content

Instantly share code, notes, and snippets.

@grasmash
Created February 3, 2017 19:26
Show Gist options
  • Select an option

  • Save grasmash/6552fcd32eced45f37020c4a63a98479 to your computer and use it in GitHub Desktop.

Select an option

Save grasmash/6552fcd32eced45f37020c4a63a98479 to your computer and use it in GitHub Desktop.
Dynamically swaps Drupal 8 menu item with a user's profile image.
<?php
// If you create a menu link titled "User Profile Image" with URL "/user",
// it will be dynamically swapped with the user's profile image.
/**
* Implements hook_link_alter().
*/
function mymodule_user_link_alter(&$variables) {
/**
* @var \Drupal\Core\Url
*/
$url = $variables['url'];
// Return early where possible.
if ($url->isExternal()) {
return;
}
else {
$route_name = $url->getRouteName();
if ($route_name == 'user.page') {
if (strtolower($variables['text']) == 'user profile image') {
/** @var \Drupal\user\Entity\User $user */
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$picture = $user->user_picture->view([
'settings' => [
'image_style' => 'mini',
],
'label' => 'hidden',
]);
$variables['text'] = drupal_render($picture);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment