2

I use a combination of Block plugins and panels to populate the layouts of the display modes of various content types.

Here's an example:

class MyBlockPlugin extends BlockBase
{
    /**
     * {@inheritdoc}
     */

    public function build()
    {
        $node = \Drupal::routeMatch()->getParameter('node');
        $profile_pic = ImageStyle::load('350x300')->buildUrl($node->field_image->entity->getFileUri());
        return [
            '#theme' => 'mytwigtheme',
            '#name' => $node->title->value,
            '#headshot' => $profile_pic
        ];
    }
}

It certainly works but I'm wondering if this is a bad path to travel because I'll have multiple block plugins loading and accessing the same node. I suppose I could access the node with a preprocess block hook but I'm assuming that will load for every block as well.

If the performance cost is trivial then I'm not too worried about redundancy. Is my method okay? If not, what would be a better way for a block plugin to access the data of the current node it appears on?

Update: Just another thought. Is me using a twig template making this a non issue as long as it's been loaded before?

2

No performance issue concerning the node entity, which is loaded only once per request and then stored in memory.

For caching between requests there are also no performance issues, because the rendered twig template(s) of a block are cached by default. But you have to make sure you provide the correct cache data, which is possible via a plugin context in the annotations (preferred) or by adding the cache metadata to the render array. See Block cache depending on current node and its last modification time

  • So the way I had doing it is mostly fine and to make it better I could just add something like ''#cache' => array( 'tags' => array('node:' . $node->id()), 'contexts' => array('url'), ),' to the render array? – Matt Sep 19 at 15:49
  • 1
    Yes, otherwise the block doesn't update when the node is modified and, even worse, it is displayed on the wrong node pages. – 4k4 Sep 19 at 16:39

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.