Member-only story

How to Embed a View in a Node in Drupal 9

In Drupal, there are different ways of embedding a view in a node. These are two of them.

Sergio Guardiola Herrador
2 min readFeb 24, 2021

When it comes to embedding a view in Drupal, there are many choices available. Normally I would recommend creating a display block in the View and adding the block to the page, but in some cases, you may want or need to embed the view in a template. These are two ways you can do that:

  1. Preprocessing the view and rendering it in twig:

The first step is to add this to your *.theme file in your theme. In this example, I’m making sure the view is only loaded in full view mode and only in content types landing page and campaign page. I needed to preset the arguments with the values selected by the editor so $string_category can have a string value like “Press” and $array_tags is an array of term ids, for example [1, 2, 3].
The view will be available in Twig using the variable blog_filter_block.

/*** Implements template_preprocess_node().* @param $variables*/function THEME_preprocess_node(&$variables) {  if ($variables['view_mode'] == 'full' && in_array($variables['node']->bundle(), ['landing_page'…

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet