I need to convert the below code added in hook_page_attachments()
and
add the external js in *.libraries.yml but not sure how to add variables like
$token and $user->mail in the *.libraries.yml so I can just attach library
drupal_add_js('http://js.acobot.com/' . check_plain($token) . '.js', 'external');
$script = 'var _aco = _aco || [];';
drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
if ($user->uid) {
$user_info = "_aco.push(['email', '" . check_plain($user->mail) . "']);";
drupal_add_js($user_info, array('type' => 'inline', 'scope' => 'footer'));
}
Add Your Script to a file In *.libraries.yml, I have added
acobot-initialise:
version: 1.x
js:
js/acobot.js: {}
dependencies:
- core/jquery
- core/drupalSettings
Added that file to the library under
$attachments['#attached']['library'][] = 'acobot/acobot-initialise';
Use drupalSettings to pass data from php to js
$attachments['#attached']['drupalSettings']['acobot']['email'] = check_plain($account->getEmail());
Added script acobot.js as follows
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.acobot = { attach: function (context, settings) { var _aco = _aco || []; _aco.push(['email', drupalSettings.acobot.email]);
} };})(jQuery, Drupal, drupalSettings);
drupalSettings
to pass data from php to js