How do you add CSS and JS files to a Drupal theme?

How do you add CSS and JS files to a Drupal theme?

Answer: To add CSS and JS files to a Drupal theme, you need to implement the `hook_library_info()` or `hook_library_info_alter()` in the theme’s `.theme` file to define the library. Then, use the `attached` property in your render array or include the library in your theme’s `.info.yml` file. Here’s a brief example:

1. In your theme `.info.yml` file, define the library:

“`yaml
libraries:
– mytheme/my-library
“`

2. Create a `mytheme.libraries.yml` file:

“`yaml
my-library:
css:
theme:
css/style.css: {}
js:
js/script.js: {}
“`

3. Attach it in your theme’s templates:

“`php
In a Twig template
{{ attachment[‘attached’][‘library’] = [‘mytheme/my-library’] }}
“`

This makes the CSS and JS files available in your Drupal theme.

Related Questions & Topics