function toc_js_node_view in Toc.js 8
Same name and namespace in other branches
- 2.0.x toc_js.module \toc_js_node_view()
Implements hook_entity_view().
File
- ./
toc_js.module, line 100 - Contains toc_js.module.
Code
function toc_js_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($display
->getComponent('toc_js')) {
/** @var \Drupal\node\NodeTypeInterface $node_type */
$node_type = $entity->type->entity;
$toc_override = $node_type
->getThirdPartySetting('toc_js_per_node', 'override', 0);
$toc_override_default = $node_type
->getThirdPartySetting('toc_js_per_node', 'override_default', 1);
// Support toc_js per node feature.
if ($entity
->hasField('toc_js_active') && $toc_override) {
// Use default override value if not set
if ($entity->toc_js_active->value == NULL) {
$entity->toc_js_active->value = $toc_override_default;
}
if (empty($entity->toc_js_active->value)) {
return;
}
}
$toc_js_settings = $node_type
->getThirdPartySettings('toc_js');
if (empty($toc_js_settings['toc_js_active'])) {
// Toc has been disabled but the extra field hasn't been disabled.
return;
}
$attributes = new Attribute([
'class' => [
'toc-js',
],
]);
$attributes
->setAttribute('id', 'toc-js-node-' . $entity
->id());
$title_attributes = new Attribute([
'class' => [
'toc-title',
'h2',
],
]);
if ($node_type
->getThirdPartySetting('toc_js', 'sticky', 0)) {
$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);
}
$build['toc_js'] = [
'#theme' => 'toc_js',
'#title' => $node_type
->getThirdPartySetting('toc_js', 'title', 'Table of contents'),
'#tag' => 'div',
'#title_attributes' => $title_attributes,
'#attributes' => $attributes,
'#entity' => $entity,
'#attached' => [
'library' => [
'toc_js/toc',
],
],
];
}
}