2

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?

mytheme.theme

 <?php
  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;
 }

block--gary-account-menu.html.twig

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

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?

2
  • Which hook/template? From where do you get $user?
    – 4uk4
    May 16, 2019 at 15:57
  • @4k4 updated the question May 16, 2019 at 16:01

1 Answer 1

5

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

1
  • 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. May 16, 2019 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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