Search code examples
htmlgoogle-tag-manager

Custom HTML tag in Google Tag Manager with variables


I have a custom html tag in my Google Tag Manager

<script>const d = 'sdfsf'; console.log(d);</script>

Now I want sdfsf to be a variable, passed to GTM from my HTML where I have GTM init snippet. Can this be achieved anyhow?


Solution

  • GTM supports the use of variables in GTM. Apart from the "usual" dataLayer method already described by Cthulchu:

    window.dataLayer = window.dataLayer || [];
    window.datalayer.push({
      "event":"upDateD",
      "d":"customValueForD"
    })
    

    Where the first line makes sure that the datalayer variable either exists or is declared, the payload is pushed as an object, and the "event" key reminds GTM to update it's internal variables to "d" becomes available as a variable in GTM.

    Then you have to go to the "variables" section inside GTM, select "new", select the "dataLayer" variable type, and give it a name - to stay consistent let's use "d" and then enter "d" as the dataLayer key.

    Now you can use the value in GTM tags by wrapping the name of your variable in double curly brackets:

    <script>console.log({{d}});</script>
    

    An alternative way is to use the "Javascript" variable type, which you set to the name of a JS variable that exists in the global namespace. You can use in the same way as dataLayer variables.

    The datalayer mostly serves as a namespace of its own, to encapsulate variable names and avoid naming collisions. If your variable already exists and has a use outside GTM, then I see nothing wrong with saving yourself a few lines and use the "Javascript" variable type (just make sure that you do not confuse this with the "Custom Javascript" type, which allows you to define an anonymous function and use the return value).