By gisle on
Im the Wallclock module, I have the following Javascript library defined in wallclock.libraries.yml:
digital:
css:
component:
css/wallclock.css: {}
js:
js/digital.js: { weight: -1 }
dependencies:
- core/jquery
- core/jquery.once
- core/drupal
- core/drupalSettings
The file js/digital.js contains:
(function ($) {
'use strict';
Drupal.behaviors.awesome = {
attach: function (context, settings) {
function startTime() {
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
min = checkTime(min);
sec = checkTime(sec);
jQuery('#digital #clock').html(hr + ' : ' + min);
var pod = ??????; // How to I pass the custom variable from the module (PHP) to Javascript?
jQuery('#digital #pod').html(pod);
setTimeout(function () { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
startTime();
}
};
}(jQuery));The library is attached to a twig template as follows:
<div id="div"></div>
{{ attach_library('wallclock/digital') }}My problem is, how do I pass the custom variable "pod" from the module (PHP) to Javascript. The point where I want this to happen is marked with "??????" in the Javascript.
Comments
See the relevant
See the relevant documentation to add your data to drupalSettings and retirve it in your script.