I'm having a weird issue with incorrect user images being displayed and it seems to be a caching issue or perhaps I am passing the user image incorrectly to my template.

Problem: If I login to a different user account I will still see the image from my account. If I rebuild the cache and then refresh the browser, I will receive the correct user image.

Am I building the user image incorrectly?


  use Drupal\user\Entity\User;

 function gary_preprocess_block(&$variables) {
  $user = User::load(\Drupal::currentUser()->id());
  $file_uri = $user->get('user_picture')->entity->getFileUri();
  dpm($file_uri); //correct uri
  $styled_image_url = ImageStyle::load("user_pic")->buildUrl($file_uri);
  dpm($styled_image_url); //correct url
  $picture = $styled_image_url;
  $variables['user_pic'] = $picture;


<div class="user-info right-menu" nav-id="{{attributes.id}}">
  <img src="{{ user_pic }}">

The variables in the theme file are correct, but the output from twig when inspected, continues to give the wrong built url to the previous user image (until the cache is flushed).

I doubt I need to delete twig cache or flush caches anytime a user pic is changed or account is switched. Anyone know what I am doing wrong here?

  • Which hook/template? From where do you get $user? – 4k4 May 16 '19 at 15:57
  • @4k4 updated the question – Matt Campbell May 16 '19 at 16:01

When you add data from the current user you also have to add this cache context:

$variables['#cache']['contexts'][] = 'user';

You can also add the cache dependencies of the user, file and image style. Then modifying one of these entities will be effective immediately, see https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

| improve this answer | |
  • Great thanks. Its worth noting that I ran into weird script errors initially like "cannot read property theme of undefined in drupal.js" when I added this line to my hook_preprocess_block. This was because I wasnt targeting my block specifically, and adding this user cache context accidentally to other blocks led to errors. – Matt Campbell May 16 '19 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.