Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 add javascript and pass data in a hook with custom module

I am building a custom module with Drupal 8. One of the requirements of the module is that it sets up a javascript file based on the configuration settings, which the user of the module sets up in module configuration.

The javascript which needs to be added to the page depends on the configuration settings. Hence I can not add it using Libraries as mentioned in this article: Adding assets to Drupal module.

I first implemented it using a block. I use Twig templates to pass the configuration variables in PHP to the twig file, and in the twig file, I have a tag to add the javascript based on the config variables. Refer Using twig templates.

The problem with this approach is that user needs to add the block on the page, and there is no UI facing element on that block. I also find it very messy.

Is there a cleaner way to add my javascript using hook and pass variables to it? I looked around and found hook_install and hook_page_attachments. So I can add Javascript, but don't know how I can pass any php variables to it.

I am new to Drupal development. Any help with this is really appreciated.

TL;DR I need to find a way to add Javascript using Drupal hook and pass some PHP variables to it.

like image 647
Akshay Khot Avatar asked Jan 04 '23 02:01

Akshay Khot


1 Answers

Use in hook_page_attachments:

$attachments['#attached']['drupalSettings']['myvar'] = $myVariable;

Then in your js (I assume you already know how to attach js library):

(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.my_custom_behavior = {
    attach: function (context, settings) {
      var strings = drupalSettings.myvar;
      ...
    }
  }

})(jQuery, Drupal, drupalSettings);

See nice Acquia tutorial for more examples.

like image 183
Dmytro Sukhovoy Avatar answered Apr 29 '23 03:04

Dmytro Sukhovoy