You are here

function _bricks_build_layout_from_items in Bricks​ 2.x

Same name and namespace in other branches
  1. 8 bricks.module \_bricks_build_layout_from_items()

Helper function for layout handling in _bricks_nest_items().

1 call to _bricks_build_layout_from_items()
_bricks_nest_items in ./bricks.module
Helper function: converts element's items to a tree structure.

File

./bricks.module, line 174

Code

function _bricks_build_layout_from_items($layout, $items) {
  $layoutPluginManager = \Drupal::service('plugin.manager.core.layout');
  if (!$layoutPluginManager
    ->hasDefinition($layout)) {
    \Drupal::messenger()
      ->addWarning(t('Layout `%layout_id` is unknown.', [
      '%layout_id' => $layout,
    ]));
    return [];
  }

  // Provide any configuration to the layout plugin if necessary.
  $layoutInstance = $layoutPluginManager
    ->createInstance($layout);
  $regionNames = $layoutInstance
    ->getPluginDefinition()
    ->getRegionNames();
  $defaultRegion = $layoutInstance
    ->getPluginDefinition()
    ->getDefaultRegion();

  // If there is just one region and is the default one,
  // add all items inside the default region.
  $use_default_region = count($regionNames) == 1 && !empty($defaultRegion);
  $regions = [];
  if ($use_default_region) {
    $regions[$defaultRegion] = $items;
  }
  else {

    // Adjust the lengths.
    $count = min(count($regionNames), count($items));
    $regionNamesSlice = array_slice($regionNames, 0, $count);
    $items = array_slice($items, 0, $count);

    // Build the content for your regions.
    $regions = array_combine($regionNamesSlice, $items);
  }

  // This builds the render array.
  return $layoutInstance
    ->build($regions);
}