How to render HTML output in hook_ENTITY_TYPE_presave() Upon node save, I want to take the value of a text field that uses a custom input filter and save the HTML-ified final version (what the input filter renders) in a second field.

I have two text fields:


Field text_main (which is never actually displayed, avoiding the performance penalty of rendering the field)
Field text_main_display (which is displayed publicly)


The field text_main uses a custom input filter that is very slow to run.  So, I want to get the rendered output of the field after running the input filter and save it to the field text_main_display.

/**
 * Implements hook_ENTITY_TYPE_presave()
 */
function MYMODULE_node_presave(NodeInterface $entity) {
  switch ($entity-&gt;getType()) {
    case 'custom_page':
      $processedResult = $entity-&gt;get('field_text_main')-&gt;view('custom_display');
      // $processedResult is now a render array. How do I render this to HTML?
      $entity-&gt;set('field_text_main_display', $processedResult);
      break;
  }
}


Reference: This post on how to render Drupal 8 fields
In hooks which are not executed in a render context use renderPlain(), see Cron error: LogicException : Render context is empty

$html = \Drupal::service('renderer')-&gt;renderPlain($processedResult);


Caveat: Text filters can bubble up metadata which you ignore by storing only the HTML. For a custom text filter this might be OK when you know it doesn't depend on cache metadata and attachments, but don't use this as a general approach. This can have security implications, like revealing data to non-authorized users.