Cache Drupal 8 Render Arrays | Drupal 8

Cache Drupal 8 Render Arrays

Submitted by editor on Fri, 06/10/2016 - 15:11
Question

Cacheability of render arrays.
How to Cache, clear cache (basend on time , tag) of a drupal 8 render array ?

Cache configuration of a renderer array (Just an exaple)

$render_array = [
  '#markup' => 'Time : ' . date("H:i:s"),
  '#cache' => [
    'keys' => ['entity_view', 'node', $node->id()],
    'contexts' => ['languages'],
    'tags' => ['node:' . $node->id()],
    'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
  ],

];

 

Example 1. Disable Cache of a render array.

$render_array = [
  '#markup' => 'Time : ' . date("H:i:s"),
  '#cache' => [
      'disabled' => TRUE,
      ],

  ];

Example 2. Time Based Cache.

$render_array = [
  '#markup' => 'Time : ' . date("H:i:s"),
  '#cache' => [
      'max_age'=> 0,
//No cache (Like 'disabled' => TRUE,)
      'max_age'=> 60, //60 seconds / 1 minute
      'max_age'=> 3600, //3600 seconds / 1 hour 
      ],
  ];

Example 3. Tags Based Cache.

$render_array = [
  '#markup' => 'Time : ' . date("H:i:s"),
  '#cache' => [
       'tags' => ['your_module' . ':' . 'your_tag'],

      ],
  ];

Link : https://www.drupal.org/developing/api/8/render/arrays/cacheability
API :  https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/group/theme_render/8.2.x

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.