Skip to content

Instantly share code, notes, and snippets.

@jfcartier
Last active March 20, 2020 02:56
Show Gist options
  • Save jfcartier/08bde7d6cbe2f08e11e7ebe721ddd2a0 to your computer and use it in GitHub Desktop.
Save jfcartier/08bde7d6cbe2f08e11e7ebe721ddd2a0 to your computer and use it in GitHub Desktop.
D8 - Passing a PHP variable to JavaScript with drupalSettings
library:
version: VERSION
js:
js/script.js: {}
dependencies:
- core/jquery
- core/drupal
- core/drupalSettings
<?php
$build = [
'#attached' => [
'drupalSettings' => [
'configPageStuff' => [
'varX' => 123456
]
]
]
];
// or
$build['#attached']['drupalSettings']['configPageStuff']['varX'] = 123456;
(function($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.moduleBehavior = {
attach: function(context) {
console.log( drupalSettings.configPageStuff.varX );
}
};
})(jQuery, Drupal, drupalSettings);
.this-is-a-test{
color: orange;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment