1

I have a Drupal 8 View with a set of rows, which are each rendered as a compact list teaser. Additionally I need to display those rows inside the same view in a another view mode (e.g. "grid teaser" with an extra image). As a result the visitor should be able to switch between the different view modes by toggling the display.

The template views-view.html.twig should contain this:

<!-- [...] -->
<!-- Display rows as list teaser -->
<div class="view-list row">
  {{ rows }}
</div>
<!-- Display rows as grid teaser -->
<div class="view-grid row">
  {{ rows_grid }}
</div>
<!-- [...] -->

I don't really know how to render those additional rows. I thought about using the hook template_preprocess_views_view:

function template_preprocess_views_view(&$variables) {

  // collect node ids
  $nids_rows = array();
  foreach ($variables['view']->result as $row){
    $nids_rows[] = $row->nid;
  }

  // load nodes
  $nodes_rows = Node::loadMultiple($nids_rows);

  if(!empty($nodes_rows)){
    // get views of nodes as grid
    $variables['rows_grid'][] = node_view_multiple($nodes_rows, 'grid');
  }
}

But the resulting render array is not in the same form like $variables['rows'] and I'm not able to loop through those rows_grid to wrap them with specific html (like in views-view-unformatted.html.twig).

Is there a function like view_load_rows($nids, $view_mode)? Or is there a way to alter the render array with some additional keys like '#theme' to get a real rows render array?

Maybe there is even an much simpler way to accomplish this. Any Ideas?

2

You can add another view display and put it below the main view output using block or view attachment.

| improve this answer | |
  • It works, although I'm still interested in rendering rows programmatically. – Philipp Michael Mar 23 '16 at 14:17
  • @PhilippMichael, did you figure out a programmatic solution? I'm looking for a similar solution at the moment. – Randell Sep 13 '18 at 1:18
  • @Randell, no I have not found a programmatic solution but I think setting up a view attachment is best practice here. I've seen this in various drupal 8 sites. – Philipp Michael Sep 20 '18 at 9:36
  • I actually went with the same solution (re: attachment). – Randell Sep 24 '18 at 22:20
  • @ya.teck can you share an example for multiple view displays in single view ? – wilNev Dec 20 '18 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.