Iron Butterfly
Iron Butterfly

Reputation: 21

Attach or include a js file in Drupal 8

$description = $this->t('See the <a onclick="drup()">drupal</a> for options.');    

In the above code, drup() is a javascript function from a js file drupaljs.js . how do I include or attach the js file in the drupal 8 module.

The following is the directory hierarchy for the code: drupal/core/modules/config_translation/src/FormElement/func.module

Upvotes: 0

Views: 3989

Answers (1)

MichaelB
MichaelB

Reputation: 89

Compared to Drupal 7, Drupal 8 only add the javascript required on the page. This means for exemple jQuery is not automatically loaded on all pages anymore.

To add a custom javascript to a page, there is now three differents steps :

  1. Save the CSS or JS to a file.
  2. Define a "library", which can contain both CSS and JS files.
  3. "Attach" the library to a render array in a hook.

To define a library, you have to create a *.librairies.yml in you module, where * is the name of your module. Then you should have something like :

cuddly-slider:
version: 1.x
  css:
    theme:
      css/cuddly-slider.css: {}
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery

As I said, jquery is not always loaded on every page, that means that if you need to use jQuery, you have to tell Drupal that your library need it, with the dependencies key.

Depending on which assets you need to have loaded, you'll want to attach the corresponding asset library in a different way. You can use multiple hooks to load your library. If you want it to be loaded on some pages, you can use the hook_page_attachments().

<?php
function contextual_page_attachments(array &$page) {
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
    return;
  }

  $page['#attached']['library'][] = 'contextual/drupal.contextual-links';
}
?>

to attach it to a twig template :

{{ attach_library('contextual/drupal.contextual-links') }}

Here is a full documentation on how to attach js file programmatically : https://www.drupal.org/developing/api/8/assets

Upvotes: 1

Related Questions