2

I have a random set of images that appear on the homepage which needs to show each time the page is refreshed. My holding page was doing this comfortably in PHP, but since building the whole site and migrating the PHP into Twig I ran into issues with the cache. I tried moving the code into a preprocess hook for the content type however that too is subject to the caching.

Is there anyway around this problem by disabling caching for anonymous users in the preprocess hook, or updating the random number variable in the cache on each reload etc.?

Ideally I'd like to avoid doing this in JS as per the recommendation here Ignore cache in preprocess function

Here is my preprocess function PHP code which feeds a loop.

function freadman_white_preprocess_node__3(&$variables) {

$imageset = (rand(1,8)); 
$time = array(
    '01:14',
    '10:37',
    '11:16',
    '09:38',
    '04:51',
    '03:24',
    '10:39',
    '10:58'
);
$date = array(
    'pm Saturday 18.08.18',
    'am Sunday 05.08.18',
    'am Sunday 05.08.18',
    'am Wednesday 15.08.18',
    'pm Tuesday 21.08.18',
    'pm Tuesday 21.08.18',
    'am Wednesday 25.07.18',
    'am Saturday 25.08.18'
);

$variables['imageCount'] = 33;
$variables['imageSet'] = $imageset; 
$variables['imageTime'] = $time[$imageset-1];
$variables['imageDate'] = $date[$imageset-1];

}
0

First, try to pass a render element with a '#cache' value set, maybe like so:

$variables['imageSet'] = [
  '#type' => 'value',
  '#value' => $imageset,
  '#cache' => [
    'max-age' => 0,
  ],
];

Next, you could try to completely disable the cache for this node (though that's probably not the best idea).

$variables['#cache']['max-age'] = 0;

And last – but quite advanced – you can provide a custom controller, that returns an uncached JSON response with your calculations and then use a little JS script that fetches the JSON via Ajax and inserts it into some placeholder selector in your markup (for the placeholder you could even provide a pseudo field to be placed at a desired position via the admin UI).

I used exactly the concept described above to build User Online Status. You can simply grab a copy and check its code to get an idea how that works.

  • Thanks for your reply @leymannx. I tried your first 2 responses however neither of those seem to have an impact. The random number returned is the same each time until I clear all caches via the performance dashboard. The 3rd option is probably a little advanced for me, but I'll try to have a look into it. – Tony Mar 6 at 3:46

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.