You are here

public function ContainerManager::getScriptAttachments in GoogleTagManager 8

Adds render array items of page attachments.

Parameters

array $attachments: The attachments render array.

Overrides ContainerManagerInterface::getScriptAttachments

File

src/Entity/ContainerManager.php, line 173

Class

ContainerManager
Defines the Google tag container manager.

Namespace

Drupal\google_tag\Entity

Code

public function getScriptAttachments(array &$attachments) {
  $ids = $this
    ->loadContainerIDs();
  $containers = $this->entityTypeManager
    ->getStorage('google_tag_container')
    ->loadMultiple($ids);
  foreach ($containers as $container) {
    if (!$container
      ->insertSnippet()) {
      continue;
    }
    if (!$this
      ->findAssets($container)) {

      // Create snippet files (e.g. after cache rebuild).
      $this
        ->createAssets($container);
    }
    static $weight = 9;
    $include_script_as_file = $this->config
      ->get('include_file');
    $include_classes = $container
      ->get('include_classes');

    // @todo Only want one data_layer snippet even with multiple containers.
    // If user sorts containers such that the first does not define the data
    // layer, then validate this or adjust for it here.
    // Sort the items being added and put the data_layer at top?
    $types = $include_classes ? [
      'data_layer',
      'script',
    ] : [
      'script',
    ];

    // Add data_layer and script snippets to head (no longer by default).
    $function = $include_script_as_file ? 'fileTag' : 'inlineTag';
    foreach ($types as $type) {
      $attachments['#attached']['html_head'][] = $container
        ->{$function}($type, $weight++);
    }
  }
}