protected function Container::dataLayerSnippet in GoogleTagManager 8
Returns JavaScript data layer snippet or adds items to data layer.
Return value
string|null The data layer snippet or NULL.
1 call to Container::dataLayerSnippet()
- Container::snippets in src/
Entity/ Container.php - Returns array of JavaScript snippets.
File
- src/
Entity/ Container.php, line 304
Class
- Container
- Defines the container configuration entity.
Namespace
Drupal\google_tag\EntityCode
protected function dataLayerSnippet() {
// Gather data.
$data_layer = $this
->variableClean('data_layer');
$whitelist = $this
->get('whitelist_classes');
$blacklist = $this
->get('blacklist_classes');
$classes = [];
$names = [
'whitelist',
'blacklist',
];
foreach ($names as $name) {
if (empty(${$name})) {
continue;
}
// @see https://www.drupal.org/files/issues/add_options_to-2851405-7.patch
// this suggests to flip order of previous two statements; yet if user
// enters a new line in textarea, then this change does not eliminate the
// empty script item. Need to trim "\n" from ends of string.
${$name} = explode("\n", ${$name});
$classes["gtm.{$name}"] = ${$name};
}
if ($classes) {
// Build data layer snippet.
$classes = json_encode($classes);
$script = <<<EOS
(function(w,l){
w[l]=w[l]||[];
w[l].push({<span class="php-variable">$classes</span>});
})(window,'{<span class="php-variable">$data_layer</span>}');
EOS;
return $this
->compactSnippet($script);
}
}