In drupal 7 you could use "views_get_view('view-name', 'view-display-name') to render a view in the theme template.

Does anyone know the way in drupal 8 to render a view in the twig template?

(My case is very simple, 2 column user profile, right column is a view of viewed user content)

Comments

Jeff Burnz’s picture

Not sure if uou can embed a view direcly in twig, however you can set it up in preprocess and print a variable...

function HOOK_preprocess_node(&$variables) {
  $variables['view_comments_recent'] = views_embed_view('comments_recent', 'default');
}

Then in your template, in this case node:

{{ view_comments_recent }}

Draven_Caine’s picture

This would work great. Where do I put preprocess? (Still learn with the twig template system )

Jeff Burnz’s picture

In a file named ThemeName.theme, which needs to be in the root of your theme.

Draven_Caine’s picture

I am running custom theme I built so everything makes sense except how to hook the user profile vs the node.

View name: content
View display name: user_vehicle_embed

Draven_Caine’s picture

This is to embed a view on the user profile.
In your .theme file add

<?php
  function theme-name_preprocess_user(&$variables) {
    $variables['variable-name'] = views_embed_view('view-name', 'view-display-name');
  }
?>

Now go to your user.html.twig and call your variable with
{{ variable-name }}

Thanks again Jeff.

Kristi Wachter’s picture

You can use Twig Tweak to get access to Views output - the Twig Tweak documentation shows simple syntax:

{{ drupal_view('who_s_new', 'block_1') }}

or more complex syntax:

{{ drupal_view('who_s_new', 'block_1', arg_1, arg_2, arg_3) }}

I hope that's helpful!

Kristi

˚ ˚ ˚ ˚ ˚
Kristi Wachter
Drupal consultant, evangelist, and enthusiast