Initializing a Javascript variable (i.e datalayer) with help of Hugo variables

Hi,
My first time using this forum. As part of my effort to adapt my website for using the Enhanced Ecommerce Google Analytics feature and tracking “product impressions”, I need to have a properly formatted ecommerce.impressions object in the dataLayer deployed into the page template preferably before the GTM container snippet. This is recommended when implementing Enhanced Ecommerce impressions by the book.
Ideally, the ecommerce object would look like below:

How can I use Hugo variables to generate this javascript variable when the page is loading? I haven’t found much explanation on the internet. The few I found where very confusing and it would be great to have some “ready to use” code that I can slightly modify. Surely someone else would have the same question later.

Thanks a lot in advance.

You can create resources on the fly with Hugo Pipes. If you can provide the logic to create the json, then you should be able to do this.

Thanks, I solved this by adding a datalayer.html file to the partials and invoking it right after the opening head tag.
Here’s what the content of the datalayer.html looks like :

<script>
var dataLayer = [];
dataLayer.push({'ecommerce':{'impressions': []}});

{{ range sort (where .Site.RegularPages "Params.type" "content_type") "Params.sort_param" "asc"  }}

   dataLayer[0]['ecommerce']['impressions'].push(
   {
     'key1':'{{ .Params.param1 }}',
     'key2':'{{ .Params.param2 }}',
     }
   );

{{ end }}

</script>