Skip to main content

Attaching Libraries

Displaying 1 - 2 of 2

How To Attach Library To A Specific Content Type

If you need to upload a library with a module during its operation, in Drupal it's called attaching file.
Attaching a library can be done in several ways depending on your needs. 
Remember that the library is always registered by its module or theme name followed by the library name. 

DrupalVIP technical notebook & support

function rwcenter_page_attachments(array &$attachments) {
	$attachments['#attached']['library'][] = 'rwcenter/content';
        
    $node = \Drupal::routeMatch()->getParameter('node') ?? \Drupal::routeMatch()->getParameter('node_preview');
    if (is_null($node)) {}
    else {
    	if ($node->getType()=='rwcenter') {
        	$attachments['#attached']['library'][] = 'rwcenter/content';
        }
    }        
}

Adding assets (CSS, JS) to a Drupal module via *.libraries.yml

In Drupal 8 and later versions, stylesheets (CSS) and JavaScript (JS), jQuery, React, and even Angular, are loaded through the same system for modules (code) and themes, for everything: asset libraries. 

Asset libraries can contain one or more CSS assets, one or more JS assets, and one or more JS settings.

Drupal uses a high-level principle: assets (CSS or JS) are only loaded if you tell Drupal it should load them. 

Drupal does not load all assets (CSS/JS) on all pages because this is bad for front-end performance.