I need to use my theme path in a jQuery script for a D8 theme I'm building. I know this is available as drupalSettings.path.baseURL (followed by the path to my theme) but how do you make this variable available to javascript? Lots of D7 info out there, not much D8.
2 Answers
You can attach the drupalSettings in any form / build / preprocess etc.
Something like :
function HOOK_preprocess_html(&$variables) {
$variables['#attached']['drupalSettings']['path']['themeUrl'] = \Drupal::theme()->getActiveTheme()->getPath();
}
-
1Thanks Dylan! It turns out the solution requires doing both what you show here, and 4k4's solution below.– JOaklandCommented Dec 5, 2016 at 20:49
To make the variables from drupalSettings available in custom javascript code, you have to add core/drupalSettings
as dependency when you define the library:
mytheme.libraries.yml
custom-javascript:
version: 1.x
js:
js/custom-javascript.js: {}
dependencies:
- core/jquery
- core/drupalSettings
mytheme.info.yml:
libraries:
- mytheme/custom-javascript
js/custom-javascript.js
(function ($, drupalSettings) {
var baseURL = drupalSettings.path.baseURL;
})(jQuery, drupalSettings);
-
Thanks! Turns out the solution requires both this answer and the one from Dylan above.– JOaklandCommented Dec 5, 2016 at 20:48