You are here

public function TocJsBlock::build in Toc.js 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Block/TocJsBlock.php \Drupal\toc_js\Plugin\Block\TocJsBlock::build()

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/TocJsBlock.php, line 263

Class

TocJsBlock
Provides a 'SocialSimpleBlock' block.

Namespace

Drupal\toc_js\Plugin\Block

Code

public function build() {
  $build = [];
  $toc_js_settings = $this->configuration;

  // toc-js class is used to initialize the toc.
  $attributes = new Attribute([
    'class' => [
      'toc-js',
    ],
  ]);
  $attributes
    ->setAttribute('id', 'toc-js-block-' . Html::cleanCssIdentifier($this->pluginId));
  $title_attributes = new Attribute([
    'class' => [
      'toc-title',
      'h2',
    ],
  ]);
  if ($this->configuration['sticky']) {
    $attributes
      ->addClass('sticky');
  }
  foreach ($toc_js_settings as $name => $setting) {
    if ($name == 'toc_js_active' || $name == 'title') {
      continue;
    }
    $data_name = 'data-' . Html::cleanCssIdentifier($name);
    $attributes
      ->setAttribute($data_name, $setting);
  }

  // Provide some entity context if available.
  $entity = NULL;
  if ($node = $this->currentRouteMatch
    ->getParameter('node')) {
    $entity = $node;
  }
  elseif ($taxonomy_term = $this->currentRouteMatch
    ->getParameter('taxonomy_term')) {
    $entity = $taxonomy_term;
  }
  $build['toc_js'] = [
    '#theme' => 'toc_js',
    '#title' => $this->configuration['title'],
    '#tag' => 'div',
    '#title_attributes' => $title_attributes,
    '#attributes' => $attributes,
    '#entity' => $entity,
    '#attached' => [
      'library' => [
        'toc_js/toc',
      ],
    ],
  ];
  return $build;
}