Score:1

How to render a twig template in the meta data of a cacheablejson response?

cn flag

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?

Score:4
cn flag

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.

Score:0
cn flag

Looks like I needed to use renderPlain instead of render

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.