How to render a view programmatically and set as node field? I am trying to render custom view and put the result as content of the node.

Here is my code 

function my_theme_preprocess_node(&amp;$variables)
{
    if (isset($variables['node']) &amp;&amp; $variables['node']-&gt;getType() == 'custom_type') {
        $reference_view = $variables['node']-&gt;field_reference_view-&gt;first();
        if (!empty($reference_view)) {
            $view_name = $reference_view-&gt;getValue()['value'];
            $view = \Drupal\views\Views::getView($view_name);
            $view-&gt;setArguments(array());
            $view-&gt;setDisplay('block');
            $view-&gt;preExecute();
            $view-&gt;execute();
            $variables['embedded_view'] = $view-&gt;buildRenderable();

        }
    }

}


But this code shows only debug message and when I try to get output in a twig template file it is empty 

    {{ node.embedded_view }}


What is wrong with my code. How can I render a view and set it as a content of node or just node field in order to print it in a twig template file.
Because your variable reference is incorrect. It should be:

{{ embedded_view }}


Since you added it to the $variables array as $variables['embedded_view'].

As an alternative you can get the Twig Tweak module. Example on the docs page:

{# You can pass arguments to the view if needed. #}
  &lt;dt&gt;View:&lt;/dt&gt;
  &lt;dd&gt;{{ drupal_view('view_name', 'page_1') }}&lt;/dd&gt;