1

Is there a way to programmatically load a views block that isn't active in the config(not placed under admin->structure->block layout).

My usual method to load a block programmatically is something like the following in hook_preprocess_node:

$block = Block::load('views_block__courses_block_3');
$block_render = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

However, that seems to just return null if I haven't placed the block into a region after creating it under views.

Also noticed that the block isn't listed in the config table until placed into a region.

2
  • 1
    Yes that's correct, blocks that aren't in regions don't get rendered. There might be a way around it (I need it too), but I haven't found one yet. Basically we now have the concept of blocks and instances of those blocks - creating the View display is creating the block, assigning it to a region in a theme is what makes the instance, and makes it available for render
    – Clive
    Commented Jan 24, 2018 at 15:08
  • @Clive, a way around it could be to create a block instance on the fly, see option b), or execute the views block display directly, see option c) of drupal.stackexchange.com/questions/153184/…
    – 4uk4
    Commented Jan 24, 2018 at 19:03

1 Answer 1

3

See this answer for details.

Basically, the way to do this is to add a "Hidden Blocks" region to your theme, then place the blocks you want to render there. The region does not get rendered so it's not a big resource drain. We do this to use have "block" paragraphs using paragraphs all the time.

2
  • I call mine Do Not Render :) Don't suppose you know of docs or an issue that suggests that method is the "official" workaround/solution for this? I'd love to put that to bed in my own mind
    – Clive
    Commented Jan 24, 2018 at 15:49
  • I know I saw some issue conversations about this when I had to figure it out. This docs.acquia.com/article/lesson-21-blocks-and-configuration talks about instances and points to the change record. The reason for instances was to allow the same blocks to be placed in different regions. I think that you can programatically create an instance but an instance requires a region. So it still shows up in the block placement UI.
    – CG Monroe
    Commented Jan 24, 2018 at 16:21

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.