7

I have created a custom block in the Drupal CMS. Say it is called "test_block". Is there a way to render this block in a template file using the name of the block?

Thanks,

2

5 Answers 5

19

D7:

<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print $block['content'];
?>

'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

In this example, 'webform' is the module's name, 'client-block-11' is the block's delta.

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

More information: http://drupal.org/node/26502

====== OR =============

<?php
//suppose 98 is the id of the block

   $block =block_load('block',98);
   $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));        
   print $output;
?>
4
  • 1
    The D7 solution won't universally work, because $block['content'] might be a renderable array instead of a string of html. Also, this method will only render the content, without the '#theme' => 'block' wrapper.
    – donquixote
    Aug 9, 2018 at 11:33
  • The other D7 solution will cause a notice or sth, because drupal_render() has a by-reference parameter.
    – donquixote
    Aug 9, 2018 at 12:29
  • Thanks :) This help me lot
    – Rayees AC
    Jul 1, 2021 at 15:48
4

D8:

$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
$rendered_block = ['#markup' => render($block_view)];

Render a custom block programmatically

2

Try this

$block = module_invoke('block', 'block_view', 'test_block');
print render($block['content']);
1
  • This doesnt solves the problem. I tried this already. Jul 7, 2014 at 10:17
0

If you are asking how to use a custom template for this block, then the answer is:

Assuming the machine name of your block is test_block, then create a file called

 block--block--test_block.tpl.php

In your theme

0

On your template level you should be able to do something like this:

<?php
  $test_block = "test_block";
  print views_embed_view($test_block);
?>

This will display your block in the template.

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .