Last updated March 28, 2016. Created on July 7, 2005.
Edited by SKAUGHT, heykarthikwithu, Elaman, caspervoogt. Log in to edit this page.

PLEASE NOTE: These snippets are user submitted. Use at your own risk. For users who have setup Drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

If you want to embed the contents of a block into a node, a custom block, custom module, or a page template, you can use the following snippets.

//D7
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);
//D6 and earlier
$block = module_invoke('module_name', 'block', 'view', 'block_delta');
print $block['content'];

To specify which block from which module, you simply edit the two following variables in the first line:

'module_name' = The machine name of the module (i.e. the module's folder name). This is true for core modules too, so for instance 'search', 'user' and 'comment' would all work here.

'block_delta' = The machine name of the block. You can determine what this is by visiting the block administration page and editing the block. The URL for editing a webform block, for instance, would be something like:

Drupal 7: admin/structure/block/manage/webform/client-block-11/configure
Drupal 6: admin/build/block/configure/webform/client-block-11

In this example, 'client-block-11' contains the block's delta, '11'.

Custom blocks will have module name of 'block' and a number for a delta, which you can also find by editing the block.

Examples

Display who is a new user.

//D7
$block = module_invoke('user', 'block_view', '2');
print render($block['content']);
//D6 and earlier
$block = module_invoke('user', 'block', 'view', 2);
print $block['content'];

Duplicate a custom block you've created.

//D7
$block = module_invoke('block', 'block_view', '1');
print render($block['content']);
//D6 and earlier
$block = module_invoke('block', 'block', 'view', 1);
print $block['content'];

Display the Font Size module's block (note the name is 'fontsize' -- the same as the module's folder).

//D7
$block = module_invoke('fontsize', 'block_view', '0');
print render($block['content']);
//D6 and earlier
$block = module_invoke('fontsize', 'block', 'view', 0);
print $block['content'];

Showing more than the block body

Calls to $block['content'] only provide the block body. Here are three ways to provide more.

1. In comments, GWL shows how to wrap the $block data in divs. It also checks for empty content and hides empty blocks:

$block = module_invoke('block', 'block', 'view', 1);
  if ($block['content']) {
    $output = "
\n"; $output .= "

".$block['subject']."

\n"; $output .= "
".$block['content']."
\n"; $output .= "
\n"; print $output; }

2. On a different page japanitrat shows how to call theme() function with a cast to object.

$block = (object) module_invoke('[target_module]', 'block', 'view', "[target_block_ID]");
print theme('block', $block);

The theme call will provide the block wrapped in your theme's block.tpl output (assuming php template). However, it may not look exactly like a block in a given sidebar (say, block appearing in center content, but rendered as if a left sidebar block). Usually this difference comes from the absence of variables determining HTML and CSS styling written in the block.tpl file.

To make a block appear in one place, themed as if for another region, that would require inspection of your theme's template.php that is outside the scope here. For an example, review the Acquia Marina template.php, line 302, 'template_preprocess_block(), for where the 'rounded block' CSS class comes from, then triangulate with that theme's block.tpl.php.

3. Damien Tournoud describes a method to render a block in Drupal 7 on a different page:

$block = block_load($module, $delta);
$render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = drupal_render($render_array);
print $output;

This mimics the way core renders blocks, and has the advantage of loading the appropriate block.tpl.php .

Advanced rendering (Drupal 7)

The above methods work great on simple sites, but they start to fail on more complex multilingual sites. The following is a helper function that will integrate with I18n Blocks module (part of the Internationalization project).

/**
 * Helper function to find and render a block.
 */
function render_block_content($module, $delta) {
  $output = '';
  if ($block = block_load($module, $delta)) {
    if ($build = module_invoke($module, 'block_view', $delta)) {
      $delta = str_replace('-', '_', $delta);
      drupal_alter(array('block_view', "block_view_{$module}_{$delta}"), $build, $block);

      if (!empty($build['content'])) {
        return is_array($build['content']) ? render($build['content']) : $build['content'];
      }
    }
  }
  return $output;
}

Usage is as simple as passing in the module and delta keys.

  print render_block_content('block', 15);

Drupal 8

In case their is an existing instance of the block in that particular layout. Then the block can be rendered by using preprocess

$block_manager = \Drupal::service('plugin.manager.block');
$block_config = [];
$block_plugin = $block_manager->createInstance('<block_id>', $block_config);
$block_build = $block_plugin->build();
$block_content = render($block_build);

Reference : http://drupal.stackexchange.com/questions/153184/programatically-render-a-block-in-a-twig-template

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

GWL’s picture

This is a GREAT snippet ... but I ran into a couple of problems when I started using it. Here are my solutions:

Problem: The snippet only prints the contents of a block, and not the block itself as it would normally appear in the sidebar. Primarily, I needed the title of the block to show, and I needed to enclose the block in a div for styling.

Solution: Just as $block['content'] calls the content of the block, $block['subject'] calls the title of the block as defined in admin>>blocks>>configure. To style it, I wrapped the whole thing in a set of divs (as done on the sidebars) and wound up with this:

  $block = module_invoke('block', 'block', 'view', 1);
  $output = "
\n"; $output .= "

".$block['subject']."

\n"; $output .= "
".$block['content']."
\n"; $output .= "
\n"; print $output;

Problem: In the sidebars, Drupal automatically hides blocks that don't have content. That doesn't happen when you pull a block elsewhere on the page. Specifically, though there's no content to show, the block title and the div formatting still display. The result is an ugly empty block.

Solution: After a little trial and error, I settled on a simple IF statement to check if $block['content'] was empty:

 $block = module_invoke('block', 'block', 'view', 1);
  if ($block['content']) {
    $output = "
\n"; $output .= "

".$block['subject']."

\n"; $output .= "
".$block['content']."
\n"; $output .= "
\n"; print $output; }

Now my non-sidebar blocks look great, and if there's no content to show, they don't display. Just like the real thing!

Gary

trentmu’s picture

I'm trying to show only child pages, like this very own drupal site does on this page: http://drupal.org/node/23220 (the child links within the page are redundant with the links on the left side.)

$block = module_invoke('user', 'block', 'view', 1);
print $block['content'];

The code above shows ALL the navigation links, but I'm trying to figure out how to restrict it to just child pages. My goal is ultimately to remove the 'expanded' menu items somehow and have it just show the child pages in the middle of the page.

Any help is apreciated!

Trent

tusik’s picture

I'm using the shortest snippet, and working fine

<?php
      $block = module_invoke('search', 'block_view', 'form');
        print render($block['content']);
?>

But I really need the h2.title to render. Has a solution been found for D7?

Koen_Vanmeerbeek’s picture

I tried to use this php code to show the feed-content of an aggregator feed on a page. It turned up to work out this way:

$block = module_invoke('aggregator', 'block', 'view', 'feed-1');
print $block['content'];

So $delta here is supposed to be of the form 'feed-x' where x stands for the number of the feed.

As If’s picture

Yes, sometimes delta is an integer, other times it is a string. If you have PHPMyAdmin (or some other way to view your db tables), look at the blocks table. In there you will find columns for the module and delta of every block you have created. The module and delta values can be used in the snippets above. Just be sure to pick one that uses your current theme.

-------------------------------------------
Interactive Worlds and Immersive Obsessions
http://www.asifproductions.com

Joscha_’s picture

It is also possible to use the standard block-templates to display the blocks:

  $block_module = 'your-module';
  $temp_block = module_invoke($block_module, 'block', 'view', 0);
  $block->subject = $temp_block['subject'];
  $block->content = $temp_block['content'];
  include( path_to_theme() . '/block-' . $block_module . '.tpl.php' );
zareen’s picture

I've been looking for the answer to this for a long time, so thanks for posting it here.

I was able to create a block with with some menu info. And then place it into a few pages on my site without any theming. First I made a new block and noted it's number (it was block/8)

Then I went to the page where I wanted the little mini-menu and put this in:

$block = module_invoke('block', 'block', 'view', 8);
print $block['content'];

It showed just fine, and now I only have to edit my mini-menu in one spot if I need a change.

Thanks

zareen’s picture

Cool. You can do it with Nice menus.

$block = module_invoke('nice_menus', 'block', 'view', 1);
print $block['content'];

I also created a new content type, added a field to the top. And then inserted the code for the nice menus block there. Now I have an editable menu within my page.

nice

JohnnyHa’s picture

This seems fine and all but what if you want to style everything ? Lets say an article.
The block outputs:

Title
Submitted by author on date
Text
Comments

How do you output this manually so you can style it ? Because i want to output the block inside a graphic so i need to position everything in detail.

How do you output for example the "Submitted by author date" for example ? Or just the headline ?

mean0dspt’s picture

this code does explain things - print $block['content'];
it means that it outputs one part of the array, namely "content"
if you investigate other segments of the array and their names, you can output them separately, like print $block['subject']; etc.

lucky_lowell’s picture

I would like to move the login block from the sidebar last to the sidebar first after log in.
Where would I look for this syntax?
thanks
lucky

ron_mahon’s picture

In D5 it's the weight settings - moves it up . In D6 just grabe the cross and drag it where you want it
Regards
Ron

scoorch’s picture

Does this method (module_invoke('user', 'block', 'view', 2);) ensure that the block caching mechanism still applies?
For example, if a block is cached for a user: will the method discussed above ensure that the block is not rebuilt when the same user views it twice? I think this is a critical performance question...

escuriola’s picture

Here is the snippet:

  <?php 
    $block = module_invoke('views', 'block', 'view', 'additional_product_view-block_1');
    print $block['content'];
  ?>

where "additional_product_view-block_1" is the delta "number". (See url or phpmyadmin to check the delta name).

Regards

neeshpal’s picture

this worked beautifully! this is indeed very useful. I am glad i found this page

<?php
  $block = module_invoke('menu', 'block', 'view', 'menu-menu1');
  print $block['content'];
 ?>

'menu '--> module
'menu-menu1' -->$delta

heres a nice explanation about how to find $delta

http://drupal.org/node/183981#comment-2265206

ericpai’s picture

I tried this but it's not displaying the block title.
I added a block from the "add block" page. It has an id of 53.

I have this code in my page.tpl.php or node.tpl.php:

<?php  
$blockTest = (object) module_invoke('block', 'block', 'view', 53);
print theme('block', $blockTest);
?>	

It does show the contents (body) of the block, but not the block title (subject).
Is this a bug?

corrie.potter’s picture

How would I go about passing in an argument to the block. I have a view that requires an argument to fetch the appropriate data and do not know how to pass it in.

benjohnstone’s picture

Damn good question, I'm keen to know the answer to this also.

Ben Johnstone

DeeLay’s picture

I have also been looking at this, I don't see any code in the hook_block function in views.module that would handle arguments, so I think the answer is that you can't.

However you could change the view and provide a default argument if an argument is not present. You can specify that it should take the nid or uid from the URL for example. Or you could use some PHP to provide the default value.

eaposztrof’s picture

The views_embed_view() can pass additional arguments to display/print view:

<?php
	print views_embed_view($view_name, $display_id, $argument); // with single argument
	print views_embed_view($view_name, $display_id, array($arg1,$arg2,$arg3)); // with multiple arguments
?>
aklump’s picture

The following 6.x code will give you more than just the contents of the block, including block admin title overrides, and other "normal" block.tpl $vars. It works on disabled blocks and is region independent. Be aware it ignores display settings for the block!!!

//get a block programmatically
//it provides all normal block properties to block.tpl.php
//it ignores user and page visibility for the block
//it ignores caching, and will not cache
//it will allow for block admin title overrides!!!
global $theme;
$block = array(
  'module' => '[type module responsible for building block here]',
  'delta' => [type the delta of this block, in given module],
  'theme' => $theme, //you could also hardcode a theme name here if you wanted, this just takes the active theme and uses it
  'subject' => '',
);
$block += (array)db_fetch_array(db_query("SELECT * FROM {blocks} WHERE delta = %d AND theme = '%s' LIMIT 1", $block['delta'], $block['theme']));
$block += module_invoke($block['module'], 'block', 'view', $block['delta']);
$block = (object)$block;
if ($block->title) {
  $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
}
$output = theme('block', $block);
jonjonz’s picture

Is it possible to insert the calendar module mini display into a node? I can't figure out what the delta would be, and have not been able modify these examples to work with the mini calendar. (version 5).

hilrap’s picture

got this code working (on page.tpl.php):

<div id="custom-block"> 
    <?php $block = module_invoke('block', 'block', 'view', 7);
print $block['content']; ?>
  </div>

Now how can I call the function for only some specific nodes? "Page specific visibility settings" in block administration will obviously be ignored...

sabrawy’s picture

how i can list all blocks in drupal no matter what comes from system or other modules

i want to list all blocks name and delta please

sabrawy’s picture

i get it by

_block_rehash()
ball.in.th’s picture

Check out Block2Field, a module I just released, to put any block as a field inside a node. No php coding needed! Arguments can be passed for Views block too!

tannerg’s picture

Why can't I get this code to work in a callback defined in a call to hook_menu?

function site_editor_nav_menu() {
$items['manage/slideshow-images'] = array (
'title' => 'Manage Slideshow Images',
'page callback' => 'manage_slideshow_images',
'access callback' => TRUE,
'menu_name' => 'site_editor',
);

function manage_slideshow_images() {
$block = module_invoke('views', 'block', 'view', 'slideshow_manager-block_1');
$blockContent = $block['content'];
return $blockContent;
}

This gives me the WSOD. Any ideas?

tannerg’s picture

because the view block I am trying to spit out was empty. Now I am checking for an empty result for the view and only running this code if there are some nodes for the view to spit out.

feo’s picture

function block_render($module, $block_id) {
  $block = stratis_block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}
ajtoelle’s picture

Don't know if stratis_block_load() is another helper function or what, but it works if you swap it out like so...

#put in template.php
function block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}
#put in whatever.tpl.php
block_render('search', 'form')
advix’s picture

Just used your snippet. It works flawlessly! Thank you!

Taiger’s picture

Note that the above function only works if you change "return" to "print" in the block_ render function.

I have been trying to find a solution to this. Thank you.

Are there any performance penalties we should be aware of with this technique?

Christian DeLoach’s picture

Just a quick note, this technique will also use the block template. The other techniques that render just the blocks content will not. This is especially helpful when using a custom block template, e.g. block--block--[block_id].tpl.php. Thank you for the code example.

rondev’s picture

Don't manage to do anything when the parameter in the hook is not delta but type like in
locale_block_view($type)
lang_dropdown_block_view($type)

Any idea to complete that:
$block = module_invoke('lang_dropdown', 'block_view', ???); render($block);

deepit887’s picture

I want to change the div position for a particular page in drupal 6. then how is this possible.

original position
<div id = "showcase">....</div>
<div id = "content">
<div id = "content-inner">..</div>
<div id = "sidebar-right:>...</div>
</div>

I want like :

<div id = "showcase">....</div>
<div id = "sidebar-right:>...</div>
<div id = "content">
<div id = "content-inner">..</div>
</div>

Please give a perfect solution.

arnoldbird’s picture

This does not work in D7 for printing a block:

<?php
$block = module_invoke('block', 'block_view', '1');
print render($block);
?>

I tried it in Bartik. It renders an empty string.
I would edit the docs but have not been able to find any code that works.

soulston’s picture

This works for me:

// Output a block anywhere.
$block = module_invoke('block', 'block_view', '8');
print render($block['content']);

You might want to try a kpr($block); assuming you have devel installed to make sure your $block actually contains some renderable arrays.

Fayna’s picture

Thank you soulston. this is the only solution that worked for me in D7. the aforementioned code in the documentation doesn't.

dizzybee’s picture

After looking for ages and trying everything...your solution of adding the ['content'] bit worked perfectly.

urlaub’s picture

Works in D 7.15:

 // Output a block anywhere.
$block = module_invoke('block', 'block_view', '8');
print render($block['content']); 

Thank you for the code update!

gurpreet2000’s picture

its work in D7

<?php
$block = module_invoke('block', 'block_view', '3');
print render($block['content']);
?>
Cablestein’s picture

Here's what I use at the bottom of my page.tpl.php, in my footer div, to duplicate the main menu:

$block = module_invoke('system', 'block_view', 'main-menu');
print render($block);

Slightly different than other menu blocks.

webfunkin’s picture

This did not work for me. I had to use print $block['content']; in Drupal 7.

GillesV28’s picture

I had this error too :
Strict warning: Only variables should be passed by reference in include() ...

My code was :

  $block = block_load('block', 2);
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block)));
  print render($output);

And now I change by this and that works well :-)

  $block = block_load('block', 2);
  $output = _block_get_renderable_array(_block_render_blocks(array($block)));
  $output2 = drupal_render($output);
  print render($output2);

I tried module invoke but that was not translated. this above yes :-)

I hope that will help you.

tusik’s picture

Hello Gilles,
you mean this is the only way for the blocks to be translated?

madhura.dhole’s picture

Below code worked for me to render custom block inside any tpl file or any other location
===============================================================================

$block = block_load($module, $delta);

$module = lets_connect;       
//
project name inside module.info file
$delta = letsconnect_form; //
go to block of your module, click on edit, url is http://www.examplesite.com/admin/structure/block/manage/lets_connect/letsconnect_form/configure letsconnect_form is the delta value for here..
$render_array = _block_get_renderable_array(_block_render_blocks(array($block))); $output = render($render_array); print $output;
joe1987uk’s picture

Thanks, this is a great post.

Would you happen to know how this could be done in Drupal 8, in a .twig file?

jukka792’s picture

This works nicely with Drupal 7, but how to show the block only to certain user roles?

$block = module_invoke('block', 'block_view', '8');
print render($block['content']);

Block settings does not take any effect.

manish sharma’s picture

check the user's role and wrap your code in the condition.

global $user;
if (in_array('YOUR_ROLE', $user->roles)){
	$block = module_invoke('block', 'block_view', '8');
	print render($block['content']);
}
chevali’s picture

I was wondering how i can invoke a cached copy or get this snippet to go to cache, i have a few invoked blocks on my site with about 3 million page views a month, and wanted to increase the performance.

Myko’s picture

If you need to print bean block in custom area or template

    $block = module_invoke('bean', 'block_view', 'BLOCK_MACHINE_NAME');
    print render($block['content']);