0

I'm attempting to create a block plugin that renders nodes retrieved from a query. I'm able to successfully get the node id's and field values from the query but I'd like to wrap each item in divs and classes but I'm not sure where to start.

public function build() {
    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post')
        ->sort('created', 'DESC')
        ->range(0,3);

    $nids = $query->execute();
    $build = [];

    foreach ($nids as $nid) {
        $node = Node::load($nid);
        $build[] = $node->field_image->view();
    }

    return $build;
}

This is able to render a list of images. But I'd like to be able to have control so I can output something like

<div class="column">
    <div class="image">
        <img src="img1.jpg">
    </div>
    <div class="bodytext">
        <p>Body Text</p>
    </div>
</div>

<div class="column">
    <div class="image">
        <img src="img2.jpg">
    </div>
    <div class="bodytext">
        <p>Body Text 2</p>
    </div>
</div>

<div class="column">
    <div class="image">
        <img src="img3.jpg">
    </div>
    <div class="bodytext">
        <p>Body Text 3</p>
    </div>
</div>

Instead of what Drupal wants to output automatically from the view() function.

1
  • You can create a custom theme (and template) for your block. That adds wrapping divs and classes to your node images.
    – Eyal
    Commented Jun 25, 2016 at 15:29

1 Answer 1

0

You can configure a custom view mode with the two fields image and body and then use a twig file:

node--blog-post--my-view-mode.html.twig

And build the node:

$build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'my_view_mode');

Alternatively your task could be easily solved in Views, but maybe this is only an simplified example and you need to do more things in code.

1
  • I agree, views would be much simpler. But we're trying to have the best performance possible, and I was under the impression that views were slow.
    – Amy
    Commented Jun 24, 2016 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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