4

I have a custom module that creates three pages. Each page has a controller, twig file, and css file. What I'd like to do is only load the css files when they are needed. I created a libraries.yml file like this:

mymodule:
  version: 1.x
  css:
    theme:
      css/page1.css: {}
      css/page2.css: {}
      css/page3.css: {}

This loads the three css files whenever I display any of the three files. What I'd like to do is somehow load page1.css only when page1 is requested. Is there a way to subdivide the libraries.yml file into sections that each specified one css file, then load it into the template with an attach_library() call or preprocessing??

Or do I need to create a separate module for each page? The reason I put the three pages in one module is they are a section of the site that share other assets.

1
  • 3
    As an aside - it’s a good idea to only use version if you intend to increment it with every change to your library. That version number forms the cache buster string for those specific js/css assets, and can cause problems if you’re using a reverse proxy like varnish otherwise. I’d you remove version, the global cache buster string will be used, which changes with cache clears, and sidesteps the issue.
    – Clive
    Dec 7, 2021 at 12:38

1 Answer 1

7

You can create multiple library entries in *.libraries.yml.

page.1:
  css:
    theme:
      css/page1.css: {}

page.2:
  css:
    theme:
      css/page2.css: {}

page.3:
  css:
    theme:
      css/page3.css: {}

Then you can attach the relevant library to the node it should be attached to using my_module.page.3 (for page three). You would do attach it to the render array being returned from your controller on the given page as follows:

class ExampleController extends ControllerBase {
  function firstPageCallback() {
    // Build your $page array (not shown).
    // Then attach:
    $page['#attached']['libraries'][] = 'my_module.page.1';
  }
}
0

Your Answer

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

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