You are here

16.3 通过hook_page_build组装区域区块

admin 的头像
Submitted by admin on 星期一, 2015-08-03 10:03

作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com

让我们来试一下,打开block.module文件,搜索block_page_build,还真找到了。真聪明,你猜对了。我们来看一下block模块的具体实现。

/**

 * Implements hook_page_build().

 *

 * Renders blocks into their regions.

 */

function block_page_build(&$page) {

  global $theme;

 

  // The theme system might not yet be initialized. We need $theme.

  drupal_theme_initialize();

 

  // Fetch a list of regions for the current theme.

  $all_regions = system_region_list($theme);

 

  $item = menu_get_item();

  if ($item['path'] != 'admin/structure/block/demo/' . $theme) {

    // Load all region content assigned via blocks.

    foreach (array_keys($all_regions) as $region) {

      // Assign blocks to region.

      if ($blocks = block_get_blocks_by_region($region)) {

        $page[$region] = $blocks;

      }

    }

    // Once we've finished attaching all blocks to the page, clear the static

    // cache to allow modules to alter the block list differently in different

    // contexts. For example, any code that triggers hook_page_build() more

    // than once in the same page request may need to alter the block list

    // differently each time, so that only certain parts of the page are

    // actually built. We do not clear the cache any earlier than this, though,

    // because it is used each time block_get_blocks_by_region() gets called

    // above.

    drupal_static_reset('block_list');

  }

  else {

    // Append region description if we are rendering the regions demo page.

    $item = menu_get_item();

    if ($item['path'] == 'admin/structure/block/demo/' . $theme) {

      $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));

      foreach ($visible_regions as $region) {

        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';

        $page[$region]['block_description'] = array(

          '#markup' => $description,

          '#weight' => 15,

        );

      }

      $page['page_top']['backlink'] = array(

        '#type' => 'link',

        '#title' => t('Exit block region demonstration'),

        '#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),

        // Add the "overlay-restore" class to indicate this link should restore

        // the context in which the region demonstration page was opened.

        '#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),

        '#weight' => -10,

      );

    }

  }

}

Block模块,在这里会找到当前主题的所有的区域,对于每个区域,会加载这个区域里面的所有的当前可用的区块。以区域的机读名字为键,把区域里面的内容追加到$page数组上来。

代码里面的

if ($item['path'] == 'admin/structure/block/demo/' . $theme) {

这是一种非常特殊的情况,只有在区块的管理界面,显示一个主题的演示区域的时候,才会用到,所以里面的代码,我们这里不用深究。


Drupal版本: