Drupal - How do I add CSS files only to the front page?
You can find exactly what you want under the topic Adding Libraries to Specific Pages at this tutorial Drupal 8 Theming Fundamentals, Part 1
To give you a real example, I am going to explain with the Bartik theme, so you can change easily.
I have created a css file cssfile.css
under the path css/cssfile.css
. Now this CSS file I want to use on only front page.
Step 1: Add the library to the theme: Add the following code in the
bartik.libraries.yml
css-filling: css: theme: css/cssfile.css: {}
Note: Here I have given the name
css-filling
to this library but you can give any other name. We will use this name in pathStep 2: Setting the code in
bartik.theme
so above perticular library(ultimately css) will only be added to front-page,function bartik_preprocess_page(&$variables) { if ($variables['is_front']) { $variables['#attached']['library'][] = 'bartik/css-filling'; } }
Note: Now in the above code the important thing is path,
bartik
part comes form thethemename
andcss-filling
comes from the step-1.
This code I have tested in my test site and it is working on front-page only.
You can attach libraries in templates, for example html.html.twig
is an ideal place to attach libraries conditional on the path. You can either use template suggestions, e.g. html--front.html.twig
or a twig expression.
The other answers revolve around preprocess, which is fine, however preprocess is an abstraction and makes theming development more opaque, i.e. it buries important information in a PHP function, rather than being obvious and clear in the template.
I'm not saying preprocess is bad, only that it depends largely on how you want to work and how opaque/abstract you want to theme.
To attach a library only for the front page in html.html.twig
we can use the not
operator and the root_path
variable as a condition:
{{ not root_path ? attach_library('my_theme/my_library') }}
If you create the template suggestion html--front.html.twig
you can attach the library unconditionally:
{{ attach_library('my_theme/my_library') }}
Make sure you have created the css you want as a library in libraries.yml
first. Then you need to use hook_preprocess_page()
like so:
/**
* Implements hook_preprocess_HOOK() for page templates.
*/
function THEMENAME_preprocess_page(&$variables) {
// Add page preprocess functions here.
if ($variables['is_front'] == TRUE) {
// Attach your css
// - replace "theme_name" with the name of your theme
// - replace "library_name" with the name of what you called
// this particular css library in libraries.yml
$variables['#attached']['library'][] = 'theme_name/library_name'
}
}
You might be better creating a page--front.html.twig
file and attaching it there instead via your libraries.yml
file. This is the preferred approach in Drupal 8.