public function RenderCache::getCacheableRenderArray

public RenderCache::getCacheableRenderArray(array $elements)

Gets a cacheable render array for a render array and its rendered output.

Given a render array and its rendered output (HTML string), return an array data structure that allows the render array and its associated metadata to be cached reliably (and is serialization-safe).

If Drupal needs additional rendering metadata to be cached at some point, consumers of this method will continue to work. Those who only cache certain parts of a render array will cease to work.

Parameters

array $elements: A render array, on which \Drupal\Core\Render\RendererInterface::render() has already been invoked.

Return value

array An array representing the cacheable data for this render array.

Overrides RenderCacheInterface::getCacheableRenderArray

File

core/lib/Drupal/Core/Render/RenderCache.php, line 321

Class

RenderCache
Wraps the caching logic for the render caching system.

Namespace

Drupal\Core\Render

Code

public function getCacheableRenderArray(array $elements) {
  $data = [
    '#markup' => $elements['#markup'],
    '#attached' => $elements['#attached'],
    '#cache' => [
      'contexts' => $elements['#cache']['contexts'],
      'tags' => $elements['#cache']['tags'],
      'max-age' => $elements['#cache']['max-age'],
    ],
  ];

  // Preserve cacheable items if specified. If we are preserving any cacheable
  // children of the element, we assume we are only interested in their
  // individual markup and not the parent's one, thus we empty it to minimize
  // the cache entry size.
  if (!empty($elements['#cache_properties']) && is_array($elements['#cache_properties'])) {
    $data['#cache_properties'] = $elements['#cache_properties'];

    // Extract all the cacheable items from the element using cache
    // properties.
    $cacheable_items = array_intersect_key($elements, array_flip($elements['#cache_properties']));
    $cacheable_children = Element::children($cacheable_items);
    if ($cacheable_children) {
      $data['#markup'] = '';
      // Cache only cacheable children's markup.
      foreach ($cacheable_children as $key) {
        // We can assume that #markup is safe at this point.
        $cacheable_items[$key] = ['#markup' => Markup::create($cacheable_items[$key]['#markup'])];
      }
    }
    $data += $cacheable_items;
  }

  $data['#markup'] = Markup::create($data['#markup']);
  return $data;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!RenderCache.php/function/RenderCache::getCacheableRenderArray/8.1.x