Sunday, February 23, 2025
HomeAnalyticsCustom Templates Guide For Google Tag Manager

Custom Templates Guide For Google Tag Manager


Last updated 12 August 2020: Added details about server-side tagging.

As I have finally managed to pick up my jaw from the floor, it’s now time to tell you what’s got me so excited. Google Tag Manager recently released a new feature called Custom Templates. Actually, it’s not fair to call it a feature. It’s a full-blown paradigm shift in how we use Google Tag Manager. It’s a suite of features designed to help brands, companies, and users create and share their own custom JavaScript and HTML setups with ease, while taking care that the code is optimized for delivery in the web browser.

Custom Templates, in short, are tag, variable, and Client templates that you can create and configure. In other words, if you have a cool idea for a tag (e.g. an analytics tracking tag for a vendor not natively supported by GTM), a variable (e.g. a Custom JavaScript variable that does something with a string), or a Client (e.g. a server-side endpoint for some new analytics tool), you can now turn them into reusable templates which can, in turn, be shared with other users and containers via template export and import. You can also use the Community gallery to distribute your templates.

Templates use a customized, sandboxed version of JavaScript, which has its own idiosyncratic vernacular that you must learn (with the help of this guide, of course). The reason for this added complexity is that with templates you can ensure that the code being executed is safe, unintrusive, and optimized.

Furthermore, templates you create will define certain permissions that are required for the template code to be able to run. An additional level of governance is provided by way of policies defined on the web page itself where the template code might be run. The interplay between these permissions and policies is a core feature of template security.

There are lots and lots of things to cover in this guide, so let’s just get started.


X


The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

How to read this guide

This is a long guide. It has to be – there’s so much about custom templates that needs to be addressed in any document whose purpose is to provide a comprehensive treatment of the subject matter.

However, don’t interpret my inability to write concise prose as indicative of how complex custom templates are. I can assure you – they’re absolutely manageable by anyone who’s been using Google Tag Manager for a while.

This guide is a reference. Its purpose is to offer you documentation to support your work with custom templates.

Because of this, I want to suggest some different ways to approach this guide.

Be sure to check out my other guide on how to create a Facebook pixel template – it should shed more light on how templates work. You can also check the corresponding video if you prefer watching rather than reading.

You can also view all the custom templates I have created and/or collected in this GitHub repository and in the Templates section of this site.

Custom Templates in a nutshell

Google Tag Manager’s Custom Templates offer a way to build a user interface around the custom code you might want to run on the site using Google Tag Manager. The user interface is what you’ve come accustomed to when using GTM’s tags and variables. It comprises text input fields, settings, tables, labels, drop-down menus, and so forth.

Obviously, the UI itself is already a huge asset. Being able to offer a user interface in lieu of a complicated code block will minimize problems arising from input errors, and will help keep the code stable.

However, the templates have another, less apparent (but no less impactful) function. They add layers of protection and security to the code they abstract. Templates use a custom JavaScript framework which introduces a handful of APIs (application programming interfaces) that you must use if you want the code to actually do anything.

This introduces a steep learning curve, because you can’t just copy-paste code from Stack Overflow any more. If you want to set a global window property, you need to use an API for that. If you want to log to console, you need to use an API for that. If you want to check the value of a cookie, guess what, you need to use an API for that.

Basically any code that tries to access the global state of the page or run any native JavaScript functions defined on the global level requires an API call.

So why this added complexity? Well, for one, these APIs make sure that potentially dangerous and/or intrusive modifications to the global state are done in a controlled manner.

Whenever you want to use an API, you must require() it in the template code. And when you introduce an API like that, the template automatically generates a set of configurable permissions for that API call.

In a nutshell, templates encapsulate the logic you would otherwise introduce with custom code. By introducing APIs with permissions, the templates can be configured to work in a secure and easily managed context.

An added level of security is the introduction of policies, where you as the site owner can add some code to the web page itself, which can have additional levels of control over how template permissions are resolved.

For example, if I have a tag configured to send hits to some endpoint, I can write a policy on the page that only allows pixel requests to one of the many endpoints configured in the tag.

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

gtag('policy', 'send_pixel', function(container, policy, data) {
  if (data.url !== 'https://snowplow.simoahava.com/i') {
    throw('Invalid pixel endpoint!');
  } else {
    return true;
  }
});

With that policy in place, the image request will only be executed if the endpoint URL is https://snowplow.simoahava.com/i. Otherwise, the tag will fail in an error, and you can see the error message in the Errors tab of Preview mode.

An additional perk of using templates is that you don’t have to add the nasty unsafe-eval keyword to your Content Security Policy. Any code run through a template is compiled into JavaScript when the container is written, and thus doesn’t require the use of eval().

Conversely, with Custom HTML tags and Custom JavaScript variables, the code is written into a string which is then compiled with eval() at runtime. This is a bad practice and requires a huge compromise in security if using a Content Security Policy.

I hope you can see the usefulness of Custom Templates. Imagine a library of Custom Templates, where anyone can share their own work for others to download and use in their containers. Smaller brands and companies could finally get their tools and platforms out there for the masses using Google Tag Manager.

Update 2 October 2019: You no longer have to imagine such a library as it now exists. Check out the Community Template Gallery as well as my introduction to it.

Getting started

Before exhausting you with all the details about custom templates (and trust me, there’s a lot to digest in the feature), I want to start by walking you through creating a tag template and a variable template. We won’t use all the most complex features for this, but it should serve as a nice intro to how custom templates work in Google Tag Manager.

Be sure to check out this guide for a walkthrough of building a Client template for server-side tagging.

Don’t forget to check out my other article, which covers the creation of a Facebook pixel template. It should provide a more comprehensive (and more overwhelming) look at how templates are created.

Tag template walkthrough

In this walkthrough, we’ll go through how to create a simple script injection tag. This is how many of the third-party vendors out there want their scripts to be loaded.

We’ll use a wonderful company called Conductrics as an example. They have developed a tool with which you can do A/B-testing and personalization, using ML-driven targeting logic, dynamic goals, server-side and client-side deployment options, and a whole host of other features to help you answer those difficult business questions you have with data.

Note! You can of course replace the Conductrics-specific stuff with some other vendor source URL, if you want. The steps you take in this guide would still be identical.

The tag template is simple, by design. Conductrics offers the option to host the required JavaScript for you, so all you need to do is add the

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments

Skip to toolbar