For consistency between modules and themes we are standardizing all asset attachment through libraries instead of including individual stylesheets and JavaScript files (that ability already was removed >6 months ago, see https://www.drupal.org/node/2228783) in a theme's THEME.info.yml
file. The assets will be defined into a named library in a theme's THEME.libraries.yml
and attached as such to the THEME.info.yml
for loading assets on all pages, or through the #attached
property of a renderable array or preprocess hook for assets that are only needed on some pages.
Before
example.info.yml
:
name: Example
type: theme
core: 8.x
stylesheets:
all:
- css/style.css
print:
- css/print.css
After
example.libraries.yml
:
libraryname:
css:
theme:
css/style.css: {}
css/print.css: { media: print }
example.info.yml
name: Example
type: theme
core: 8.x
libraries:
- example/libraryname
Optional: Themes with more granular libraries
If you then e.g. want to load CSS to style nodes differently, but only want to load that CSS when actually necessary, you can expand example.libraries.yml
to:
libraryname:
css:
theme:
css/style.css: {}
css/print.css: { media: print }
node:
css:
theme:
css/node.css: {}
and in example.theme
:
function example_preprocess_node(&$variables) {
$variables['#attached']['library'][] = 'example/node';
}
This encourages logical groupings of assets to aid in correct order of dependencies (and note that it also allows you to put the associated JS in there as well), e.g.:
libraryname:
css:
theme:
css/style.css: {}
css/print.css: { media: print }
node:
css:
theme:
css/node.css: {}
node-article:
js:
js/reading-time-indicator.js: {}
css:
theme:
css/article.css: {}
dependencies:
- example/node
node-blog:
css:
theme:
css/blog.css: {}
dependencies:
- example/node
Optional: SMACCS categorization
Note: the theme
key in those YML files refers to the SMACSS structure used by Drupal 8, see https://www.drupal.org/node/1887922. If you don't care about SMACSS, use theme
. If you do care about SMACSS, you can split up the style.css
in the above example into more granular files, per SMACCS category:
libraryname:
css:
layout:
css/grid.css: {}
component:
css/buttons.css: {}
css/lists.css: {}
css/pager.css: {}
css/tables.css: {}
css/tabs.css: {}
theme:
css/style.css: {}
css/print.css: { media: print }
Optional: library-per-SMACCS-category
You could go even further, and create a library per SMACSS category for easier overriding in subthemes:
example.libraries.yml
:
layout:
css:
layout:
css/grid.css: {}
component:
css:
component:
css/buttons.css: {}
css/lists.css: {}
css/pager.css: {}
css/tables.css: {}
css/tabs.css: {}
theme:
css:
theme:
css/style.css: {}
css/print.css: { media: print }
example.info.yml
name: Example
type: theme
core: 8.x
libraries:
- example/layout
- example/component
- example/theme
For comprehensive docs, see https://www.drupal.org/theme-guide/8/assets