🇬🇧
Drupal Documentation and Guides
Guides
English
English
  • Getting Started with Drupal
  • Installing Drupal
  • Drush
  • Theme & Module Development Concepts
  • Modules
  • Themes
  • FrontEnd
    • Javascript
  • Backend
    • Helpful Drupal Classes and Methods
    • Entities
    • Nodes
    • Taxonomies
    • Hooks
    • Twig
    • Libraries
    • Queries
    • Forms
    • Files & Images
    • Helpful functions and solutions
  • Guides
    • Custom Fields
      • Entity Reference and integer
      • Two Text Fields
      • Textfields, formatted text and numbers
      • Links and media elements
Powered by GitBook
On this page
  • Attach a Library using hooks
  • Attach a library to a specific page
  • Attach library to specific form
  • Attach library from twig file
  1. Backend

Libraries

Libraries are a way to group and manage JavaScript, CSS, and other assets.

They are used to provide a consistent way to include assets in Drupal. Libraries are defined in a .libraries.yml file, which is placed in the module or theme directory. The .libraries.yml file defines the library name, version, and the files that are included in the library. Libraries can be attached to a page or a specific element in a page.

Attach a Library using hooks

Attach a library to a specific page

function THEMENAME_preprocess_page(&$variables){
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/mypath') {
    $variables['#attached']['library'][] = 'library/name';
  }
}

Attach library to specific form

function MODULE_NAME_form_alter(&$form, &$form_state, $form_id)
{

  if ($form_id == 'FORM_ID') {
    $form['#attached']['library'][] = 'MODULE_NAME/LIBRARY_NAME';
  }
}

Attach library from twig file

{{ attach_library('library/name') }}
PreviousTwigNextQueries

Last updated 2 years ago