Skip to content

Instantly share code, notes, and snippets.

@rpayanm
Last active March 5, 2021 20:37
Show Gist options
  • Save rpayanm/71e13d14f2959a3456a8e793636e799b to your computer and use it in GitHub Desktop.
Save rpayanm/71e13d14f2959a3456a8e793636e799b to your computer and use it in GitHub Desktop.

The friendly.libraries.yml file will look like this:

friendly-greeting:
  version: 1.0
  license: GPL
  js:
    js/friendly-greeting.js: { }
  dependencies:
    - core/drupalSettings

We'll make use of hook_page_attachments_alter to add our asset library and our custom variables to the page.

/**
* Implements hook_page_attachments_alter().
*/
function friendly_page_attachments_alter(array &$page) {
  // We're going to pass along the user's display name to our front-end code.
  $account = \Drupal::currentUser();
  if ($account->isAuthenticated()) {
    // First we attach our asset library to the page.
    $page['#attached']['library'][] = 'friendly/friendly-greeting';
    // Then we pass along our dynamic value.
    // This will then be available in our JavaScript as drupalSettings.friendly.name.
    $page['#attached']['drupalSettings']['friendly']['name'] = $account->getDisplayName();
  }
}

In our theme, in the js/friendly-greeting.js file we now do whatever we need to with the user's display name variable.

(function ($, Drupal, drupalSettings) {
 // ...
 // If we have a nice user name, let's replace the
 // site name with a greeting.
 if (drupalSettings.friendly.name) {
   var siteName = document.getElementsByClassName('site-branding__name')[0];
   siteName.getElementsByTagName('a')[0].innerHTML = '<h1>Howdy, ' + drupalSettings.friendly.name + '!</h1>';
 }
 // ...
})(jQuery, Drupal, drupalSettings);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment