1

In a json response I'm returning some prerendered data. However I got tired of constructing the html by concatenating strings in php and decided to make a twig template for it.

$render_facets_arr = [
  '#theme' => 'facets',
  '#facets' => $data['meta']['facets'],
];
$data['meta']['renderedFacetsTest'] = \Drupal::service('renderer')->render($render_facets_arr)->__toString(); 

However when I do so I get this error

LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\Core\Cache\CacheableJsonResponse.

I saw this question but I don't think it'd applied because I didn't need to change the context the query was done in, I just wanted to add the rendered twig with some variables filled in. LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected

Any ideas? Should I just go back to constructing the html as strings in php?

2 Answers 2

4

Use renderRoot() and, most importantly, add the cache metadata of the build array (after it was rendered) to the response, so that the response can be invalidated in cache if necessary:

use Drupal\Core\Cache\CacheableMetadata;

  $build_facets = [
    '#theme' => 'facets',
    '#facets' => $data['meta']['facets'],
  ];
  $data['meta']['renderedFacetsTest'] = (string) \Drupal::service('renderer')
    ->renderRoot($build_facets);

  $response = new CacheableJsonResponse($data);
  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build_facets));
  return $response;

By returning a response with the rendered result the controller takes control of the entire rendering process and the rendering becomes the top level render call in this request, which makes it a renderRoot() call.

0

Looks like I needed to use renderPlain instead of render

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.