I have a content type 'homepage' containing one node which is used a the homepage. This node has a multivalue image field, and I need to randomly select one of those images to show on the homepage on every site visit. I have written the logic for this in the THEME_preprocess_node function in my THEME.theme file. This is working fine, but the site in question is still in development mode with most caching deactivated. I'm worried that once the site goes live and the caching is activated, it will serve the homepage from cache and therefore always show the same image until the cached version of the page expires.
Is that the case, or are the preprocess functions evaluated on every page visit even when the cache is active? If not, how can I circumvent this to get a random image every time?
This is the code I have written for this:
$imgages = $node->get('field_frontpage_header_image'); $random = $imgs->get(rand(0, $imgages->count() - 1))->getValue(); $img = File::load($random['target_id']); $variables['random_header_image'] = ImageStyle::load('frontpage_header')->buildUrl($img->getFileUri()); I then use {{ random_header_image }} in the twig template. Maybe I can change this variable to a render array with a cache setting of max-age => 0? Not sure if this works in preprocess functions though ...
Thanks!