2

Normally, to attach javascript (settings or just a library) to a Drupal 8 node type (page), you should use template_preprocess_node and add it to the #attached array. (example)

Problem with the display suite is that the function is never reached. So you can't add the library and optionally the settings for that library to that node.

Although the hook_preprocess_field function would suffice, I have the issue that I want to add it to a non-renderable field. So the field will never be displayed. I just need some javascript settings based on that field.


Example:

I have a node type: background_carousel_page With a field: images (field type: image, multiple allowed)

I need to be able to add the images url to the settings of javascript to make the carousel displaying the images.


So to summarize: I need a solution where I can add the library + settings to a specific node based on a field that's not being rendered.

  • Have you tried adding it in the twig file for that field with {{ attach_library(library) }}? – Kevin Mar 13 '17 at 16:13
  • But the inclusion and settings are dependant on a field. The use of the attach_library is only for inclusion of files, not settings? Correct me if I'm wrong ;) – ReBa Mar 13 '17 at 16:17
5

try hook_entity_view or hook_node_view_alter:

/**
 * Implements hook_entity_view().
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'background_carousel_page' && $view_mode == 'full') {
    $build['#attached']['library'][] = 'mymodule/mylibrary';
  }

}

or

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_node_view_alter(array &$build) {
  // @see \Drupal\Tests\embed\Functional\EmbedPreviewTest::testPreview
  $build['#attached']['library'][] = 'mymodule/mylibrary';
}
  • I think this is the most correct answer, as it is independent of the display suite module. You can use the display suite function hook_ds_pre_render_alter and add it to the vars['#attached'] array there. – ReBa Mar 20 '17 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.