1

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 <script> 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.

2

You can add variables into the scope without generating a Javascript file and then use a hook like preprocess_html to add them in:

$variables['#attached']['drupalSettings']['mymodule']['config']['color'] = $config->get('mymodule.color');

These value(s) are then available in the drupalSettings scope, which you can read out in your module Javascript file in order to do things. Just pass drupalSettings into it.

  • Thanks @Kevin, where do I add the above line? in preprocess_html hook, I guess? and to access the values in JS, where do I pass drupalSettings? – Akshay Khot Dec 5 '17 at 20:31
  • There are examples on this page: drupal.org/docs/8/api/javascript-api/javascript-api-overview - basically declare in your module that it depends on core/drupalSettings in its libraries.yml, then pass it into the function hook. That is listed here: drupal.org/node/2274843 – Kevin Dec 5 '17 at 20:32
  • thanks for the details @Kevin, I tried that but somehow it's not receiving data. I have updated my question. Can you please have a look? – Akshay Khot Dec 5 '17 at 21:59
  • Just realized I was adding hooks in a wrong file! instead of ae.module, I added them in ae.install. It's working as expected, thanks! – Akshay Khot Dec 6 '17 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.