How to safely render node body on a custom variable? I created a custom template for my programmatically created block.

I defined a variable for the template called test

so in my render array I have

'#test' =&gt; $node-&gt;get('body')-&gt;value


Problem is when I print {{ test }} in my twig template, it literally prints the html rather than rendering it. Ex: &lt;p&gt; My node body &lt;/p&gt;

I've also have tried:

'#test' =&gt; $node


Then on twig {{ test.body.value }}

but same result, the html does not get rendered. 

The only way I found to make render is by doing {{ test.body.value|raw }} but raw filter should never be used on user entered data. 

How can I make Drupal stop escaping the html safely?
Build a render element processed_text and set the text format from the body field, so that the right text filters are applied before you print the field with {{ body }}:

If you have the node in #test like in your second example:

'#test' =&gt; $node


then you can build the render element in twig:

{% set body = {
  '#type':   'processed_text',
  '#text':    test.body.value,
  '#format':  test.body.format,
} %}

{{ body }}


This is the preferred method, see the documentation of check_markup():


  Note: this function should only be used when filtering text for use
  elsewhere  than on a rendered HTML page. If this is part of a HTML
  page, then a  renderable array with a #type 'processed_text' element
  should be used instead  of this, because that will allow cacheability
  metadata to be set and bubbled  up and attachments to be associated
  (assets, placeholders, etc.). In other  words: if you are presenting
  the filtered text in a HTML page, the only way  this will be presented
  correctly, is by using the 'processed_text' element.


https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check_markup/8.2.x



Render element in php:

'#test' =&gt; [
  '#type' =&gt; 'processed_text',
  '#text' =&gt; $node-&gt;body-&gt;value,
  '#format' =&gt; $node-&gt;body-&gt;format,
],


and print in twig:

{{ test }}