1

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 2

6

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();
}
1
  • 1
    Thanks Dylan! It turns out the solution requires doing both what you show here, and 4k4's solution below. Commented Dec 5, 2016 at 20:49
4

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);
1
  • Thanks! Turns out the solution requires both this answer and the one from Dylan above. Commented Dec 5, 2016 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.