You are here

4 理解区块的呈现

admin 的头像
Submitted by admin on 星期五, 2015-06-26 09:36

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

    在一个页面请求周期内,在构建页面呈现数组时,Drupal允许模块通过实现钩子函数hook_page_build,向页面数组追加其它元素。区块系统通过实现这个钩子函数,把所有区域作为页面元素添加了进来。

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;

      }

    }

  ...

  }

  ...

}

 

在每个区域对应的呈现数组中,包含了里面所有启用的区块。

 

function block_get_blocks_by_region($region) {

  $build = array();

  if ($list = block_list($region)) {

    $build = _block_get_renderable_array($list);

  }

  return $build;

}

 

区域内所有区块共同组成了区域呈现数组:

function _block_get_renderable_array($list = array()) {

  $weight = 0;

  $build = array();

  foreach ($list as $key => $block) {

    $build[$key] = $block->content;

    unset($block->content);


    //...

    //添加区块的上下文链接,system_mainsystem_help除外

    if ($key != 'system_main' && $key != 'system_help') {

      $build[$key]['#contextual_links']['block'] = array('admin/structure/block/manage', array($block->module, $block->delta));

    }

 

    $build[$key] += array(

      '#block' => $block, 

      '#weight' => ++$weight,

    );

    $build[$key]['#theme_wrappers'][] = 'block';

  }

  $build['#sorted'] = TRUE;

  return $build;

}

 

    还记得我们在前面表单系统一章中,讲到的呈现数组吧,是的,区块区域的显示,也采用了呈现数组。在构建呈现数组中,我们对主题内的所有可用区域进行迭代,然后又对区域内所有区块进行迭代。有关呈现数组的相关知识,可参看表单API一章。


Drupal版本: