0

Developing a D8 theme, I am loading an external .js file containing some jQuery code (so it is not inside the TWIG template).

Is it possible to access and modify TWIG variables like {{ myvariable }} inside the external jQuery?

1 Answer 1

2

It's not possible to access Twig variables in jQuery directly. Instead access the content of PHP variables inside of an external jQuery code by attaching them to drupalSettings. See the documentation:

Attaching configurable JavaScript

In some cases, you may want to add JavaScript to a page that depends on some computed PHP information.

In this case, create a JavaScript file, define and attach a library just like before, but also attach JavaScript settings and have that JavaScript file read those settings, via drupalSettings (the successor to Drupal 7's Drupal.settings). However, to make drupalSettings available to our JavaScript file, we have to do the same work as we had to do to make jQuery available: we have to declare a dependency on it.

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

and

$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

Where 'bar' is some calculated value.

Then cuddly-slider.js will be able to access

drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

https://www.drupal.org/developing/api/8/assets

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.