Google Global Site Tag (gtag.js) tracking code insertion issue

I thought I would revive this thread since I had to figure it out today having first run into what @Hyperbytes describes above.

Here’s what works:

I store the tenant script(s) in the database as it is provided by the vendor (GA, FB pixel, etc.) For example for GA:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XYYYYYYYZ"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XYYYYYYYZ');
</script>

I have a load_layout API which is called by the Server Side Data Server Connect on the layout.

Screenshot 2023-11-14 at 1.39.15 PM

This API load_layout outputs the value from the database (simple single query with output on)

In the head of the layout, I insert the script

<head>
    <script src="/dmxAppConnect/dmxAppConnect.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" crossorigin="anonymous"></script>

    <%-_('snippet.head_start')%>
    ...
</head>

snippet is the name of the single query and head_start is the column name/alias.

The part I had to work on is the syntax of the template. I’ve always used <%=_ %> which causes the script to end up in a <text> tag down in the body along with any scripts that follow.

By changing to <%-_ %> (dash instead of equal) it outputs the unescaped value.

More about the ejs templating at: https://github.com/mde/ejs#tags

2 Likes