Module Development

Use Lazy Builders and Placeholders for Drupal 8, 9, and 10

The Render API is capable of detecting poorly-cacheable (highly dynamic) parts of a page and rendering them later using a process called auto-placeholdering. This works by using #lazy_builder callbacks to lazy load certain very dynamic subtrees of a render array. The place in the array where that very dynamic content would appear is first assigned a placeholder. At the very last moment it is replaced with the actual content.

This allows Drupal to do things like cache the overall page in the Dynamic Page Cache despite parts of the page being too dynamic to be worth caching. It also allows the Render API to assemble a page using cache fragments combined with non-cacheable elements.

In this tutorial we'll:

  • Discuss what lazy builders are and how they work in conjunction with placeholders to speed up the rendering pipeline
  • Cover some common gotchas for lazy builders
  • Look at some example code that implements a lazy builder callback

By the end of this tutorial, you should know how and when to use the #lazy_builder property of a render array and how Drupal uses placeholders to increase the cacheability of content and speed up the rendering process.