Score:4

Loading individual css files for custom modules

in flag

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.

cn flag
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.
Score:7
de flag

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';
  }
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.