3

I have a render array and I want to convert it to HTML and place it in a WYSIWYG field. What is the generally accepted way to do that since drupal_render() is deprecated?

6

It was replaced with the renderer service.

$render_service = \Drupal::service('renderer');

As mpdonadio and 4k4 have pointed out in the comments, to prevent metadata from bubbling up to the main request, you should execute this in a new render context. You can do so by using the renderPlain method, rather than the usual render method (unless you're returning this from a controller, in which case use renderRoot instead).

$rendered = $render_service->renderPlain($build);
  • 1
    Shouldn't that be done in a new render context to prevent any metadata from bubbling to the main one for the page? – mpdonadio Mar 5 at 20:05
  • @mpdonadio I'm sure you're right, but I haven't found it necessary the one or two times I've used this. Probably a result of where/when I'm calling it – Clive Mar 5 at 20:07
  • 1
    Yes, in this case you should use a new render context, with \Drupal::service('renderer')->renderPlain($renderArray) or ->renderRoot() if this delivers the result from a controller. – 4k4 Mar 5 at 20:12
  • @4k4 Thanks for the info, that's very useful to know. I incorporated it into the answer – Clive Mar 5 at 20:16
  • @rjacobsen0 You're very welcome, but please see the edit as it has some potentially important information :) – Clive Mar 5 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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