Drupal 8 - Loading a library globally from a custom module

I've create the library (example-libraries.yml):

example:
  version: VERSION
  js:
    js/example.js: {}
  css:
    theme:
      css/example.css: {}

I've tried to load it globally by doing this (example.info.yml):

name: Example Module
type: module
description: "A module that is responsible for ..."
package: Custom

core: 8.x
version: 1.0-SNAPSHOT

libraries:
  - example/example

I can load it successfully for a particular Form by doing:

$form['#attached']['library'][] = 'example/example';

Any idea on how I can get it to work globally?

Upvotes: 0

Views: 2268

Answers (3)

I've finally figured that out. My custom module will place an extra tab as a child of the system.admin menu. Every other tab had an icon and I wanted to place my custom module icon there as well.

In case somebody else gets stuck with the same problem, in the file example.module, I had to create an entry:

/**
 * Implements hook_toolbar().
 */
function example_toolbar() {
    $items['example'] = array(
        '#type' => 'toolbar_item',
        '#attached' => array(
            'library' => array(
                'example/example',
            ),
        ),
    );

    return $items;
}

Upvotes: 1

Dmytro Sukhovoy
Dmytro Sukhovoy

Reputation: 992

You don't need a custom theme for this. Use hook_page_attachments():

/**
 * Implements hook_page_attachments().
 */
function example_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'example/example';
}

Upvotes: 0

Arnold PÉTER
Arnold PÉTER

Reputation: 146

It is very simple in your my_theme.info.yml you add :

libraries:

- example/example

https://www.drupal.org/docs/8/theming-drupal-8/defining-a-theme-with-an-infoyml-file

Upvotes: 0

Related Questions