Fluffy does Bad Things with his Friends
Step 2: Define an Asset Library
Libraries need to be declared in your libraries.yml file as follows:
Here are all the styling levels:
- Base - CSS_BASE = -200
- Layout - CSS_LAYOUT = -200
- Component - CSS_COMPONENT = -200
- State - CSS_STATE = -200
- Theme - CSS_THEME = -200
jQuery is still included in Drupal’s core.
Step 3: Attach the Library
Fluffy Loves Cookies
Here's the cookie-time code:
Don't act like you're not impressed...
Here's Fluffy in action.
To attach a library to all instances of a certain #type, use this hook.
Here’s an example.
Make sure to clear your cache after implementing this function so Drupal is aware of the new addition.
*Please note that Drupal will ‘de-dupe’ libraries so that if you attach the same library to multiple fields, it will still only be rendered once--let’s keep it DRY, folks.
Specific instance of #type
If you’re building a block plugin you can attach the libraries to the render array with the ‘build()’ function of your class, extending the BlockBase class.
Pages (all or subset of)
When an asset library is associated with an entire page rather than a specific part, use hook_page_attachments().
‘bar’ is some calculated value
Adding Attributes to Script Elements
To add attributes on a script tag you need to add an ‘attributes’ key to the JSON following the script URL. Within the object following the attributes key, add the attribute name you want to appear on the script as a new key. The value for the key will be the attribute value, if it is set to ‘true’ the attribute will appear on its own without a value on the element. For example, this
will create the following.
The Big No-No
Affecting the Entire Page
Externally Hosted Libraries
Differences Between D7 and D8
Drupal 7 libraries were defined with the ‘hook_library_info()’ function, but have been replaced by the ‘*.libraries.yml’ file in Drupal 8
The following functions have been replaced by ‘#attached’ in Drupal 8.
Drupal 8 settings are now stored in an external JSON file.
For the previous post in this series, click here.