0

I have added mycustomblock to the header region in our settings (/admin/structure/block). We are using the standard content block and displaying that in the Content region, which is displayed below the Header region.

For just our Basic Page content type, we would like to move the mycustomblock to display below another field. We tried using the mymodule_preprocess_node hook to move the block below one of the fields (i.e. field_categories). However, we don't know how to move the block.

How would we move the block inside the hook_preprocess_node?

Setup:

Basic Page content type

  • Title
  • Categories (field_categories)
  • Tags (field_tags)
  • Image (field_image)

node--page--full.html.twig

{{ label }}
{{ content.field_image }}

/* I want to display the block here, using some variable */
{{ mycustomblock_variable }}

{{ content.field_categories }}
{{ content.field_tags }}

Regions (order displayed: top down)

  1. header
  2. content
  3. footer

We tried the following but it didn't work

function mymodule_preprocess_node($variables) {
  $node = $variables['elements']['#node'];

  if($node->bundle() == 'page') {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(123456);// BLOCK_ID
    $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'mycustomblock');
    $variables['mycustomblock_variable'] = $block_view;
  }
}
0

I think you should send render of the block not an array of block entity.
View Method return an array.

Try with renderer service like the following:

/**
 * Implements hook__preprocess_HOOK().
 */
function mymodule_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  if ($node->bundle() == 'page') {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(12345);//BLOCK_ID
    $block_view = \Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
     // Change here default by your block view mode
      ->view($block_entity, 'default');
    $variables['mycustomblock_variable'] =\Drupal::service('renderer')->renderRoot($block_view);
  }
}
  • the renderer service was able to get us what i was looking for. – usernameabc Dec 19 '19 at 21:20

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.