1

Is it possible? To use the viewBuilder of an entity to generate the complete html and save that output into a string instead of sending it to a browser.

It would open the possibility to have email messages render using twig templates.

I have been poking around the different services and using the renderer service I can render the page-specific output as html but I can't find a way to get the complete HTML code into a string.

Matt.

7

Your question is "render a drupal 8 entity in a string". This is an example how to do this. Get an entity. Get a view builder for the entity node and us it to build your render array with the display mode "full". Render this with renderRoot to the string $html.

$node = \Drupal::entityManager()->getStorage('node')->load($nodeid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$renderarray = $view_builder->view($node, 'full');
$html = \Drupal::service('renderer')->renderPlain($renderarray);

You can do this for any entity. By default this will use the node.html.twig as configured in your theme. But you can change your render array before rendering.

Edit: For emails use renderPlain().

  • tried this but then I get a partial HTML starting from the title field – DragonEye Nov 2 '15 at 19:24
  • In $html is the whole entity rendered as a string. If you want to add more html, you can put this into your own version of node.html.twig (make your own view mode and use it instead of 'full' and name your twig to use this view mode), or put more elements in the render array before rendering or put html before and after $html. – 4k4 Nov 2 '15 at 21:39

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.