cmcintosh's picture

Things have radically changed when it comes to including javascript in your projects for Drupal 8.  Below I will break down handling External Javascript, Inline Javascript, and passing information from PHP to Javascript.

Javascript Libraries

In Drupal 7 you could use Libraries API or drupal_add_js in order to add any javascript file or setting onto any page.  In Drupal 8 things are a bit more complex so now you will need to use a libraries Yaml file.  In this YAML file you will want to define the various javascript or css resources you need for a element.

In order to let Drupal 8 know about the javascript or css asset we will create a new yaml file with the specifics on how we are handling the javascript file. Below I have examples on adding both locally hosted javascript to Drupal 8 as well as adding remote javascript libraries to Drupal 8.

Local javascript files that you are looking to add to your module or theme can be added like this:

By adding the {preprocess: false} flag you can disable javascript preprocess and aggregation on specific files.

Including Assets that are hosted elsewhere like Angular can be handled in a similar fashion like this:

Once you have your yaml file created and stored in your Theme or Module directory, you then will need to load the library you defined. There are a couple of different ways this is done depending on your use case, below I will talk about each of them:

Adding a Javascript Library inside of a Drupal 8 Twig Template file:

Adding a Javascript Library to a Drupal 8 Render Array

Finally something that has drove me nuts today, how to pass variables from PHP to Javascript in Drupal 8, or what happened to drupal.settings. In Drupal 8 you need to add your settings to the #attached array when rendering your content. Below is an example on how to do that:

Add new comment