I have to send node content by mail using an API. I manage to load and render the content to use it with my API class, and to send it. But when Drupal render the node, all URLs and image SRC are relatives, and it can't be used in a mail.

Here is the code I got so far

$node = \Drupal::entityTypeManager()->getStorage('node')->load($test_node); // $test_node is a (integer) NID
$renderBuilder = \Drupal::entityTypeManager()->getViewBuilder('node');
$node_view = $renderBuilder->view($node, $view_mode); // $view_mode is define in my admin settings
$html = \Drupal::service('renderer')->render($node_view); // I also tried renderRoot and renderPlain
dump($html); // URLs are relatives

I really search for days now, and I cannot figure how to tell Drupal Renderer to use absolute URL to generate the HTML string.


1 Answer 1


Two possible approaches:

  1. Find the URLs in preprocess targeting this specific view mode and apply setAbsolute(), see for example How do I render the absolute URL of a referenced entity in a simplenews newsletter?

  2. Apply a regex on the rendered output $html or use Html::transformRootRelativeUrlsToAbsolute() like added recently to the core MailManager:

    $html = Markup::create(Html::transformRootRelativeUrlsToAbsolute((string) $html, \Drupal::request()->getSchemeAndHttpHost()));

    Source: https://git.drupalcode.org/project/drupal/commit/530f7ac

By the way, use instead of render() the method renderPlain(), see How to deal with Bubbleable Metadata when there's no rendering context and no render array

  • I wouldn't try to search for all url, file uri or image path in a preprocess function, but the Html::transformRootRelativeUrlsToAbsolute() method is exactly what I was looking for. Thanks a lot 4k4
    – TytooF
    Oct 11, 2019 at 13:29

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.