Drupal settings

Another powerful thing we can do (and something we often need to do) is pass values from our PHP code to the JavaScript layer. In custom PHP applications, this can get messy, but Drupal has a robust API that transforms PHP arrays into JavaScript objects. These can be found inside the settings object passed to the behavior's attach() function.

Again, the easiest way to understand this is through an example. So let's say we want to print an extra message after the salutation if it is the afternoon. Of course, we can use JavaScript to determine that as well, but so far it has been the responsibility of our PHP code, so let's keep it that way. So then we need a way to tell our JavaScript that it is afternoon, and we can do this by setting a flag if that is the case, as follows:

if ((int) $time->format('G') >= 12 && (int) $time->format('G') < 18) {
$render['#salutation']['#markup'] = $this->t('Good afternoon');
$render['#attached']['drupalSettings']['hello_world']['hello_world_clock']['afternoon'] = TRUE;
return $render;
}

New here is the second line from within the if conditional, namely the one where we attach something to the render array. In this case, though, it's not a library but drupalSettings in a big multidimensional array. The best practice is to namespace our settings hierarchically like so: our module name -> the functionality the setting belongs to -> the setting name. In JavaScript, this array will be transformed into an object.

To get the drupalSettings to work, we need to make sure the core/drupalSettings library is loaded. In our case, this happens because the core/drupal library lists it as a dependency.

Now that we pass this flag (which could be much more complex if needed), we can make use of it in JavaScript:

var clock = '<div>The time is <span class="clock"></span></div>'; 
if (settings.hello_world != undefined && settings.hello_world.hello_world_clock.afternoon != undefined) { 
  clock += 'Are you having a nice day?'; 
}  

That is pretty much it. We managed to easily pass values from PHP into JavaScript and use them in client-side logic.