0

I have a block I would like to add it to my renderable array (given to a page callback), with prefix and suffix - what's the cleanest way to do this?

I understand I can do it this way:

$markup = '';
if ($block = block_load('views','results_anonymous-block')) {
    $block_content = _block_render_blocks(array($block));
    $build = _block_get_renderable_array($block_content);
    $markup = drupal_render($build);
}


$content['page'] = array(

    '#markup' => $markup,
);

return $content;

But wondered if there was a better way (e.g. without rendering the block or using the private function).

  • Why don't just put a region where you need it, and put your block in that region? – Mołot Oct 19 '15 at 14:21
  • You need to get the block in render array format and attach it to your render array. There are several answers about this in this site, I guess. I udnerstand that you want the block 'inside' your render array, otherwise you can use standard block system. – sanzante Oct 19 '15 at 14:21
  • In the main content section? before or after the main content or inside the content section? – sanzante Oct 19 '15 at 14:33
  • Inside, so I can add further markup before and after. (e.g. a general solution where the block is nested) – james_alvarez Oct 19 '15 at 14:34
  • Care to leave a comment for the downvote? Seems a prefectly reasonable question to me. – james_alvarez Oct 20 '15 at 10:40
2

Modules provide their block titles and contents through implementations of hook_block_view(). If you're looking for something similar to your posted code that doesn't rely on calls to private functions, what's below should give you a render-ready array that you can place anywhere within another render array.

$renderable_block_data = module_invoke('views', 'block_view', 'results_anonymous-block');
$renderable_block_contents = $renderable_block_data['content'];

Caveat: while the docs for D7's version of hook_block_view() suggest that the returned "content" key should be a render array, some modules/blocks may be implemented in such a way that they return plain HTML strings, in which case you'd need to put the content in a #markup element before adding them to your parent render array.

Further discussion can be found in this drupal.org post.

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.