How to insert a block into a node or template in D

2019-03-07 19:35发布

In Drupal 6, it was easy to insert a block into a template with the following code:

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

However, using the same instructions in Drupal 7 does not seem to work. I have looked around and cannot find the new method.

Does Drupal 7 have a routine that can allow for programmatically inserting a block into a template or node?

15条回答
走好不送
2楼-- · 2019-03-07 20:32

In my search to include a block in a template, i came across this post.

As an addition, if you want to include a custom block (that you added through the block interface) you have to use (instead of block_load(); in drupal 7)

$block = block_get_custom_block($bid);
$content = $block['body'];
查看更多
冷血范
3楼-- · 2019-03-07 20:34

This work for me:

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楼-- · 2019-03-07 20:36

The module_invoke() function works. However, I found that rendering a block this way apparently won't use a custom template for that block. This might be OK depending upon your needs.

As commented before in other answers, this works as well and also makes use of custom templates:

$raw_block = block_load('your-module', 'delta');
$rendered_block = drupal_render(_block_get_renderable_array(_block_render_blocks(array($raw_block))));
print $rendered_block;

So, if you have a custom block--your-module--delta.tpl.php template file, it will be used to format the block.

Source: http://api.drupal.org/api/drupal/includes!module.inc/function/module_invoke/7

查看更多
贪生不怕死
5楼-- · 2019-03-07 20:36

module_invoke Working fine for render block in the template file, but it's not working multilingual sites.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-03-07 20:37

There's module called insert_block for those which want to insert block "Drupal way" (not to program anything, just enable the module). Here's how to set it up.

NOTE: I know this question is about "programmatically inserting a block into a template or node" but Google sends people here even their are looking for non-programmer solution like me.

查看更多
叼着烟拽天下
7楼-- · 2019-03-07 20:38

For some reason render() doesn't work for me, but this does:

<?php
    $block = module_invoke('block', 'block_view', '1');
    echo $block['content'];
?>
查看更多
登录 后发表回答