1

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;
  }
}
1
  • If you only want to add the libraries to nodes, then rather than using hook_page_attachments() which will affect all pages, you could use hook_ENTITY_TYPE_view().
    – Andy
    Jul 19, 2018 at 11:36

2 Answers 2

0

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.

5
  • updated the code to have proper library names. Are you considering a config object one option, but another one could be to have a field on a particular content type that would add the libraries? Jul 6, 2018 at 17:39
  • 1
    Depends on how you want to offer the option, but as long as the names are correct, you can loop and attach them all the same.
    – Kevin
    Jul 6, 2018 at 17:41
  • 1
    If you store whether to add the libraries in a config/content entity, don't forget to add it as a cacheable dependency to the page to ensure pages get flushed when the entity is changed. (IIUC you should add the dependency even if you're not attaching a library - that way when you later configure it to add the library the cache will be flushed appropriately.)
    – Andy
    Jul 10, 2018 at 13:22
  • @Andy is this what you are referring to CacheableDependencyInterface & friends? Jul 17, 2018 at 15:38
  • 1
    @usernameabc yup - that page gives the theory, and you can find an example here.
    – Andy
    Jul 19, 2018 at 11:17
0

Replace:

js:
    path/to/library/file1.js

With

js:
    path/to/library/file1.js: {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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