Drupal 7 - How To Print Blocks In Templates

Tutorial on printing stuff from templates.

You should preprocess variables for templates.

Printing the blocks

/* Print custom block content */
$block = module_invoke('block','block_view','1');
print render($block['content']);

/* Print the whole custom block (with divs, title etc.) */
$block = block_load('block','1');
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

/* Print a views block */
$block = module_invoke('views','block_view','print_block_test_view-block');
print render($block);

Parameters for the functions:

$module = module name (like block or views)

$hook = hook inside the module to invoke (like block_view)

$delta = identifier of the block (like test_view-block or 1)

You can find the right module and delta name for the block when hovering configure link in blocks page in admin/structure/block

Like this:

  • /admin/structure/block/manage/block/1/configure
  • /admin/structure/block/manage/views/test_view-block/configure

An example:

Create a custom block in admin/structure/block/add:

Create an article node/add/article:

Create a view to show that article admin/structure/views/add:

Save & exit

Create a template for article (node–article.tpl.php) in themes/bartik/templates/

Edit the template and use the code to print these above the $content:

$custom_block = module_invoke('block','block_view','1');
$whole_block = block_load('block','1'); // not really the whole block until render
$views_block = module_invoke('views','block_view','test_view-block');

print render($custom_block['content']);
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($whole_block))));
print render($views_block);

Now you have something like this above the article content:

Remember to flush caches.

Samuli Natri (Entrepreneur, WDTutorials.com founder) has been building websites since the late 90's. He attended Helsinki University Of Technology (Computer Science) and Helsinki University (Social Sciences).

Latest Tutorial How To Translate A Website

Copyright @ 2018 WDTutorials.com. All rights reserved. Privacy policy.Terms Of Service.