6

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?

2 Answers 2

8

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);
6
  • 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
    Commented Mar 5, 2019 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
    Commented Mar 5, 2019 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.
    – 4uk4
    Commented Mar 5, 2019 at 20:12
  • @4k4 Thanks for the info, that's very useful to know. I incorporated it into the answer
    – Clive
    Commented Mar 5, 2019 at 20:16
  • @rjacobsen0 You're very welcome, but please see the edit as it has some potentially important information :)
    – Clive
    Commented Mar 5, 2019 at 20:17
1

This documentation is the best place to have the most accurate/up-to-date documentation about the rendering pipeline and its methods - such as drupal_render() - in Drupal 8+.

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.