Last active
March 20, 2020 02:56
-
-
Save jfcartier/08bde7d6cbe2f08e11e7ebe721ddd2a0 to your computer and use it in GitHub Desktop.
D8 - Passing a PHP variable to JavaScript with drupalSettings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library: | |
version: VERSION | |
js: | |
js/script.js: {} | |
dependencies: | |
- core/jquery | |
- core/drupal | |
- core/drupalSettings |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$build = [ | |
'#attached' => [ | |
'drupalSettings' => [ | |
'configPageStuff' => [ | |
'varX' => 123456 | |
] | |
] | |
] | |
]; | |
// or | |
$build['#attached']['drupalSettings']['configPageStuff']['varX'] = 123456; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($, Drupal, drupalSettings) { | |
'use strict'; | |
Drupal.behaviors.moduleBehavior = { | |
attach: function(context) { | |
console.log( drupalSettings.configPageStuff.varX ); | |
} | |
}; | |
})(jQuery, Drupal, drupalSettings); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.this-is-a-test{ | |
color: orange; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment