How to add module libraries to the page through an admin page?

by usernameabc   Last Updated July 06, 2018 18:07 PM

Looking for some guidance on how to create a custom module, mymodule, that will pull all the libraries from the custom module and display it in an admin screen. Once the libraries are displayed, I want to be able to set Add to Pages (checkbox) for each library to determine if it should be added to the nodes. It would be ideal if the setting became a configuration.

The goal is to be able to add any libraries I need to the custom module, but selectively add them to nodes using hook_page_attachments. How would I do this?

I initially tried this, but couldn't find a way to get all the libraries.

mymodule.libraries.yml

library1:
  version: 1.x
  header: true
  js:
    path/to/library/file1.js

library2:
  version: 1.x
  js: 
    /path/to/library/file2.js

mymodule.module

/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$attachments) {
  $libraries = [
    'mymodule/library1',
    'mymodule/library2',
  ];

  foreach($libraries as $library) {
    $attachments['#attached']['library'][] = $library;
  }
}


Answers 1


Your module is referencing the library names wrong. It should be “mymodule/library_name” instead of just the library name.

As long as you get that right, it wouldn’t be hard to loop node field values or a config object and add them like that.

Kevin
Kevin
July 06, 2018 17:30 PM

Related Questions