0

I want to show a block with related nodes. The function getRelatedArticles() is a complex one and I can't build it with views. Is it possible to use the method viewMultiple() and output the list as item-list? If not, what would be the best practisce becide looping over the array and build the render array for each node? Something similar to the following code (which obviously does not work):

class RelatedArticleBlock  extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $related_nids = $this->getRelatedArticles();

    $nodes = Node::loadMultiple($related_nids);
    $block['content'] = [
      '#theme' => 'item_list',
      '#list_type' => 'ul',
      '#wrapper_attributes' => [
        'class' => [
          'row',
        ],
      ],
      // I want to do something like:
      // '#items' => \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'teaser'),
    ];

    // I would like to avoid the following, build each node on it's own.  
    foreach ($nodes as $node) {
      $block['content']['#items'][] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
    }

    return $block;
  }
}
  • What is your reasoning behind not wanting to loop through and build each node? Curiosity on how to write cleaner code, or something else? – Jaypan Mar 31 at 0:40
  • Yes, for performance reasons. I read viewMultiple() has a better performance than just view() ... but didn't dive into details. – LarS Mar 31 at 0:46
  • I see that EntityViewBuilder::viewMultiple (api.drupal.org/api/drupal/…) exists, so it should work, Have you tried it and run into an error? – Jaypan Mar 31 at 0:56
1

viewMultiple() also optimizes the rendering process by returning a common #pre_render callback in the build array, see the discussions and linked topics here Twig: "for" does not display variable content without first displaying all variable content, so you can't put the output directly in #items.

So building each node on its own is the way to go and you probably won't find any differences in performance, because both methods result in the same caching mechanism.

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.