What's the preprocess function for targeting the home page in my Drupal 8?


Ok, here's what I'm trying to do. I want to apply a javascript to the front page of my site only. Here's what I'm trying:

function mytheme_preprocess_page(&$variables) {
  if ($variables[‘is_front’]) {
    $variables[‘#attached’][‘library’][] = ‘mytheme/home_page_jquery’;

The $variables['#attached'] line doesn't seem to work as it keeps giving me the website encountered an unexpected error error.

I got the idea to use this non-working code from https://www.drupal.org/node/2216195.

  • The home/front page is now a page view called Frontpage with url/path of /node so you may have to give more details on what you're trying to achieve with the preprocess. – No Sssweat Aug 17 '16 at 8:44
  • 1
    Thanks for your comment I added what I'm trying to accomplish. Should have just done so from the beginning. – Sage Aug 17 '16 at 18:28
  • PHP doesn't use and as string delimiters. You are using the wrong string delimiter in $variables[‘is_front’] and the next line. – kiamlaluno Aug 17 '16 at 18:32
  • good grief, I see what you mean. thanks for pointing out the obvious! – Sage Aug 17 '16 at 18:48

To target the front page in a preprocess function you need a condition, because for preprocess you can't use name suggestions:

function mytheme_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    // your code

What you call home page, for Drupal is the front page. The suggestion given by system_theme_suggestions_page() for the front page is page__front; similarly, system_theme_suggestions_html() suggests html__front. There aren't other suggestions.

If by home page you mean a page that is not the front page, you need to implement your own hook_theme_suggestions_HOOK().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.