Passing Ampersands through document.write with Google Tag Manager

I ran into an issue implementing some tagging using Google Tag Manager (GTM) which I’m sharing here because I had a difficult time finding a solution within StackOverflow, the Google Tag Manager Google Group, or with an increasingly-frustrating series of Google searches.

The tag that I was attempting to implement needed to be dynamically-generated based on the top-level directory of the page that was being called.  The code looked something like this:

<script src="http://some.domain.com/tag.js?variable1=dynamic&variable2=static"></script>

To call the tag by defining and substituting the dynamic variable in that url I created the following logical flow within GTM:
1.  Extract the top-level directory from the current page url’s path by using a macro.
2.  Use the value of that macro to determine the appropriate variable value using a lookup table macro.
3.  Call the script tag, substituting the proper variable.

The tag for step 3 was an HTML tag with document.write supported.  It looked something like this:

<script src="http://some.domain.com/tag.js?variable1={{pathvariable}}&variable2=static" type="text/javascript">

…and it didn’t work.  The tag was being rewritten with an HTML-equivalent ampersand (& being rewritten to &amp;), which was breaking the call:

<script src="http://some.domain.com/tag.js?variable1=correct_variable&amp;variable2=static" type="text/javascript">

document.write automatically HTML-encodes ampersands.   Google Tag Manager relies heavily on JavaScript’s document.write() method to add these tags as executable snippets in the document object.  Turning off the document.write() doesn’t let the tag fire.  Was I out of luck?  According to Stack Overflow, I was.

However, I was able to make it work, simply by adding another macro to the process and using JavaScript’s built-in decodeURIComponent() method.

My final process was:
1.  Extract the top-level directory from the current page url’s path by using a macro.
2.  Use the value of that macro to determine the appropriate variable value using a lookup table macro.
3.  Create a fully-formed url for the tag as a macro by concatenating the variable value within the rest of the url.
4.  Call the script tag, declaring the value of the url macro as a JavaScript variable and then passing that variable to a script tag that is then executed via the document.write method.

My final HTML tag looked something like this:

<script>
tagurl = decodeURIComponent("{{tag_url_macro}}");
document.write('<script src="' + tagurl + '"></script>');
</script>

If you are a user of Google Tag Manager that needs to expose data that contains an ampersand while using document.write, hopefully this will save you some time.