Understanding Drupal's Render API
Render arrays, lazy builders, attachments, and cache metadata explained as one performance model.
Render arrays are Drupal’s structured description of output. Their real power is not the final HTML; it is the metadata that lets Drupal compose, vary, invalidate, and progressively deliver that output correctly.
Markup plus metadata
A render array can describe theme hooks, children, libraries, placeholders, and caching. Cache contexts answer “what varies?”, tags answer “what invalidates?”, and max-age answers “how long?”. Missing metadata can produce either stale output or needless cache misses.
Lazy builders isolate expensive variation
A lazy builder defers a small fragment and gives Drupal the opportunity to placeholder it. BigPipe can send the stable page shell first and replace personalized or slow fragments later.
The callable must return a render array and receive only scalar arguments. Keep it deterministic and attach the same cacheability the direct build would have required.
Bubbleability is the contract
Cacheability and asset attachments bubble from children to parents. Avoid rendering early into strings because doing so discards that composition model. Return render arrays until Drupal’s main renderer owns the final conversion.
Working example
return [
'#lazy_builder' => ['portfolio.user_summary:build', [$account_id]],
'#create_placeholder' => TRUE,
'#cache' => [
'contexts' => ['user'],
'tags' => ['user:' . $account_id],
],
];Key Takeaways
- Cache contexts, tags, and max-age solve different problems.
- Use lazy builders for small, expensive, highly variable fragments.
- Do not flatten render arrays before Drupal can bubble metadata.