Drupal - How to render two views in the same twig template

The reason you get the same content is due to the #cache property of the render array you get when you call the render() method.

Most specifically, by calling setOffset() earlier in your code, you are implicitly setting a cache key on the render array, (see here):

$this->element['#cache']['keys'][] = 'offset:' . $offset;

This cache key setting, in combination with the #theme property of the render array (views_view), which is the same for both views, will result in getting a cached version of the first one when including the second one, since the [#theme] + [#cache][keys] combination is identical for both views.

To work around that you could:

  1. Remove caching completely for these views, or
  2. Avoid using setOffset(), or
  3. Add more specific keys to the cache so that you have a different cache for each view. E.g.

    $variables['viewCalls']['#cache']['keys'] = 
      array_merge(
        $variables['viewCalls']['#cache']['keys'], 
        array('viewCalls')
      );
    ...
    $variables['viewAppointments']['#cache']['keys'] = 
      array_merge(
        $variables['viewAppointments']['#cache']['keys'],
        array('viewAppointments')
      );
    

I tested your case using the 3. option and it worked as expected, I think before resolving to using another module, you could try sticking to your original code and appropriately modifying the #cache property of both render arrays.

Good luck!


Render two views in the same Twig template with the render element view:

$variables['viewCalls'] = [
  '#type' => 'view',
  '#name' => 'view_calls',
  '#display_id' => 'default',
  '#arguments' => [$variables['node']->id()],
];

$variables['viewAppointments'] = [
  '#type' => 'view',
  '#name' => 'view_appointments',
  '#display_id' => 'default',
  '#arguments' => [$variables['node']->id()],
];

There's at least one typo in your code. Remove the space in $variables['viewAppointments '].


Alternatively you could also use Twig Tweak. Which will provide you a function you can use to place views directly in your templates.

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

Twig Tweak is a small module which provides a Twig extension with some useful functions and filters that can improve development experience.

Read the full guide on Twig Tweak and Views.

Twig Tweak's drupal_view() method provide's access to embed views within any Twig code, including dynamically from within each row of another view. This feature provides an alternate method to accomplish the nesting provided by the Views field view module.

Tags:

Views

Theming

8