Our Articles about the Web and Drupal

The right way to embed Drupal blocks

Most Drupal sites use the block module to create blocks which are reused throughout a site. Have you ever needed to embed one of these custom blocks into a node template or into some other template files? Its surprising, but there isn't a single, simple function that you can call to do this. There is a thread on drupal.org about this, but none of the solutions really seemed right. To do this more elegantly, we made a function which can be used in your theme's template.php file to make block embedding simple.

  1. /**
  2.  * Returns a fully themed custom made block from the block module
  3.  */
  4. function mytheme_render_block($delta) {
  5.   $block = db_fetch_object(db_query('SELECT DISTINCT(b.bid), title, body, format from {boxes} left join {blocks} b on boxes.bid = b.delta where module="block" and boxes.bid= %d',$delta));
  6.   $block->content = check_markup($block->body, $block->format, FALSE);
  7.   $block->module = 'block';
  8.   $block->delta = $block->bid;
  9.   return theme('block', $block);
  10. }

Then, in your node template file, all you need to do is to call the function with the block's delta. To find the block delta, go to the block administration page at '/admin/build/block' and hover over the block's configure link. In the browser's status bar at the bottom, you'll see a link like 'http://mysite.com/admin/build/block/configure/block/4'. The last digit is the delta. All that remains is to place the following clean code snippet into your template and you'll have the full, properly rendered block.

  1. print mytheme_render_block(4);

With this your template files will stay clean and simple, instead of being full of code, so your themers can focus on making your site look great.

Share this

Let's start talking about your project!

Let's start talking about your project!