Main website
Government Drupal Developers NetworkCommunity

Getting Started Solved

First Drupal role: how do I get my head around render arrays?

Started by Ciara Byrne on · 336 views · 4 replies · 12 likes

CB

Ciara ByrneStarted the thread

Junior Developer, Office of Public Works ·

I'm comfortable with PHP and Twig, but render arrays still feel like magic. When should I return a render array instead of just rendering a template? And what are #cache keys actually doing?

Any pointers (docs, talks, examples) very welcome 🙏

Accepted answerSee it in the thread
PS

Priya ShahModerator

Lead Drupal Developer, Government Digital Service ·

Great question. Think of a render array as a description of output that Drupal can still change, cache and combine before it becomes HTML. Return one almost always.

return [
  '#theme' => 'service_card',
  '#service' => $service,
  '#cache' => [
    'tags' => $service->getCacheTags(),   // invalidate when it changes
    'contexts' => ['user.roles'],          // vary by role
    'max-age' => 3600,
  ],
];
  • tags: what data this depends on
  • contexts: who/where it varies by
  • max-age: how long it's valid

The "Cacheability of render arrays" page on drupal.org is the best single read.

4 replies

  1. Priya ShahModerator

    Lead Drupal Developer, Government Digital Service ·

    #1

    Accepted answer

    Great question. Think of a render array as a description of output that Drupal can still change, cache and combine before it becomes HTML. Return one almost always.

    return [
      '#theme' => 'service_card',
      '#service' => $service,
      '#cache' => [
        'tags' => $service->getCacheTags(),   // invalidate when it changes
        'contexts' => ['user.roles'],          // vary by role
        'max-age' => 3600,
      ],
    ];
    
    • tags: what data this depends on
    • contexts: who/where it varies by
    • max-age: how long it's valid

    The "Cacheability of render arrays" page on drupal.org is the best single read.

  2. Marcus Bell

    Senior Developer, Brighton & Hove City Council ·

    #2

    Also install Webprofiler locally. Seeing cache hits and misses for each block made it click for me.

  3. Daniel Ortiz

    Drupal Architect, General Services Administration ·

    #3

    Rule of thumb: if you call render() yourself in a controller, you've probably lost cacheability metadata somewhere.

  4. Ciara ByrneStarted the thread

    Junior Developer, Office of Public Works ·

    #4

    This is so helpful, thank you all! Priya's example is now pinned above my desk 😄

Join the conversation

GDDN is for people working on Drupal in government. Log in or apply to reply.