Score:-2

How to enqueue CSS to administrator side via module

cn flag

I have a custom Drupal module and I would like to enqueue its CSS to the administrator side. I've tried to add it to the .info.yml file.

css:
  theme:
    admin-styles.css: {}

I also implemented hook_page_attachments() in the module as described in Custom module for adding CSS file in admin section.

function admin_css_page_attachments(array &$attachments) {
  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
  if ($is_admin) {
    $attachments['#attached']['library'][] = 'admin-styles.css';
  }
}

I still don't see the CSS file in the source code of the administrator panel.

berliner avatar
bd flag
As mentioned in the link you added, the `css` declaration needs to be in an `*.libraries.yml` file, not in the `*.info.yml`.
cn flag
@berliner thanks but it doesn't help
cn flag
That won't work verbatim in a libraries file, you need to give it an id/key as well, and make sure you use `module_name/key` in the `$attachments` array. Check out the libraries documentation for full info. You also need to rebuild Drupal's cache after making the change to make it show up
Score:0
de flag

You need to define your library in *.libraries.yml:

example_theme.libraries.yml:

my_library:
  css:
    theme:
      admin-styles.css: {}

Then you can add this library using example_theme/my_library.

cn flag
Should it work in the case of a module or just of a theme?
Jaypan avatar
de flag
You can implement `*.libraries.yml` to define libraries in both libraries and themes. The prefix will be the machine name of the module/theme (the `*` in the name of the `.yml` file, which is `example_theme` my answer above).
cn flag
Ok, I did, but it still doesn't help. Should it be a `<link>` with href like `/modules/my_module/admin-styles.css` in the source code of admin page or my CSS is added to one of files by the path `/sites/default/files/css/` ?
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.