Skip to main content
changed title to be more accurate and clear
Link
Amy
  • 5.8k
  • 13
  • 66
  • 133

Styling and adding Adding markup to elementsfields in block pluginplugins

Source Link
Amy
  • 5.8k
  • 13
  • 66
  • 133

Styling and adding markup to elements in block plugin

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.