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?