While the example appears to work superficially (the rendered array is cached and on subsequent page loads the cached version is displayed) it doesn't actually prevent the expensive thing from happening which is really the main thing you would want. The example doesn't make this very easy to see. It is easier to demonstrate if you rearrange things a bit, moving the markup text into a separate function:
'#markup' => render_example_cache_expensive(),
And in that function calling drupal_set_message() so you can easily see when that function has been called.
function render_example_cache_expensive() {
$interval = 60;
$time = t('The current time was %time when this was cached. Updated every %interval seconds', array('%time' => date('r'), '%interval' => $interval));
drupal_set_message($time);
return $time;
}
Now when you reload the example page you can see that the function is called on each page load, the time in the message is current and the time in the rendered array is cached.
Apparently the correct way to handle this is to put your expensive thing in a pre_render function so that drupal_render() will only execute it if it is loading the non-cached version of the array. A patch is attached.
| Comment | File | Size | Author |
|---|---|---|---|
| examples-render-cache.patch | 2.26 KB | gilgabar |
Comments
Comment #1
rfayThanks for the patch!
Comment #2
rfayCommited - D7: de7e916, D8: 45b8a98
Thanks so much!
@gilgabar since your head is in this it would be wonderful if you could take a look at #1304502: [critical] Theming Example and Render Example are broken. It's a D8 issue, but apparently it's a result of just not doing the render example right.