Skip to main content
Category:

In this tuto, I'll show you how to attach a library to page(s) in Drupal 8.

Attach a library in a preprocess function

Example 1: add a library to node.

/**
 * @param $variables
 */
function THEMENAME_preprocess_node(&$variables)
{
    // check we have a node object.
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
        if ($node->id() == 237) {
            //attach the library.
            $variables['#attached']['library'][] = 'your_theme/library_name';
        }
    }
}

Example 1: add a library to maintenance page.

/**
 * @param $variables
 */
function yourmodule_preprocess_maintenance_page(&$variables) {
    $variables['#attached']['library'][] =  'your_module/library_name';
}

Example 2: attach library to specific page.

/**
 * @param $variables
 */
function THEMENAME_preprocess_page(&$variables) {
    if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
        $variables['#attached']['library'][] = 'THEMENAME/home-lib';
    }
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        if($node->getType() == 'article') {
            $variables['#attached']['library'][] = 'THEMENAME/news-lib';
        }
    }
}

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook