Skip to main content

How to add library only for front page in Drupal

You can load library only for front page in Drupal by getting the route name after matching the front page view file.

  • Loading library only for front page in drupal

    function mytheme_preprocess_page(&$variables) {
      if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
            $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
        }
    }

    You can use above code snippet to load the library only for front page in Drupal. Here we use if condition which helps you to get the route name and match the route to specified route name and load the library if condition is true.

  • Back to code snippet queries related drupal