You are here

function datalayer_page_attachments in dataLayer 8

Implements hook_page_attachments().

Load all meta tags for this page.

File

./datalayer.module, line 70
Client-side data space.

Code

function datalayer_page_attachments(array &$attachments) {
  if (empty($attachments['#attached'])) {
    $attachments['#attached'] = [];
  }
  if (empty($attachments['#attached']['html_head'])) {
    $attachments['#attached']['html_head'] = [];
  }
  $datalayer_attachment = datalayer_get_data_from_page();
  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => 'window.dataLayer = window.dataLayer || []; window.dataLayer.push(' . Json::encode($datalayer_attachment) . ');',
    ],
    'datalayers-js',
  ];

  // Include data-layer-helper library.
  if (\Drupal::config('datalayer.settings')
    ->get('lib_helper')) {
    $attachments['#attached']['library'][] = 'datalayer/helper';
  }

  // Output configred language data.
  $languages = \Drupal::languageManager()
    ->getLanguages();
  if (count($languages)) {
    $langs = [];
    foreach ($languages as $id => $language) {
      $langs[$id] = [
        'id' => $id,
        'name' => $language
          ->getName(),
        'direction' => $language
          ->getDirection(),
        'weight' => $language
          ->getWeight(),
      ];
      if ($language
        ->isDefault()) {
        $attachments['#attached']['drupalSettings']['dataLayer']['defaultLang'] = $id;
      }
    }
    $attachments['#attached']['drupalSettings']['dataLayer']['languages'] = $langs;
  }

  // Common datalayer JS.
  $attachments['#attached']['library'][] = 'datalayer/behaviors';
}