How to use custom templates in Google Tag Manager

The ‘custom templates’ in Google Tag Manager allows you to create your own tag and variable templates which you can share with others in your organization.

You can use custom templates as standard tag templates along with built-in tags.

What are custom templates?

Using custom templates, you can write your own tag and variable definitions, so that others can use them within an organization and use them alongside the built-in tags and variables.

Custom templates are more safe, efficient and easy-to-use compared to normal custom HTML tags because of their sandbox nature and permission-centric functionality.

Custom templates allow you to create a hassle-free user interface around a tag, instead of writing custom code. This user interface is similar to the built-in tags available in GTM.

Let’s take an example, suppose that you want to set a custom first-party cookie on the browser which sets Campaign ID (taken from query string parameter) for the visitor. You would normally have to write code which looks like the code below:

However, if you use a custom tag template it will be more user friendly. You just need to give a cookie name and select your cookie value along with expiry type and that’s it.

Imagine if you have to set multiple cookies based on country domain and that too with different expiry times. You would have to create dozens of bits of code for every country website and then test it to see if it is working or not. It would be a very time consuming and frustrating activity. However, if you just create a custom tag template then it’s going to take just a few minutes.

Tag template overview

In continuation with the above example, we are going to show the step by step method of creating a tag template. Follow the below steps in order to create your tag template

Step 1: Navigate to Google Tag Manager Console and click on ‘Templates’ on the left-side menu:

Step 2: Click on ‘New’ in the upper-right corner under ‘Tag Template’ and you will see the interface as below

Step 3: Now fill in your tag template information in the ‘Info’ tab.

Name: The template name that will be presented to GTM users. This name will appear in many places such as the type picker in GTM UI.

Description: (Optional) A short description of the template.

Icon: (Optional) An icon for the template. It will be shown in the editor and the type picker. Only PNG, JPEG, and GIF images are supported. The file size must be less than 50KB. Make sure to select only images that you have the right to use. (I am leaving the icon field blank for now)

Checkbox: (Optional) Mark the ‘Agree to community template gallery terms of service’ checkbox if you want to submit your tag to the gallery.

Step 4: Now click on the adjacent tab named ‘Fields’.

The field tab is used to create the user interface for the users. Here we will build the tag interface and how it will take input with some validation points. Click on ‘Add Field’.

An overlay will open on the right-hand side with the different types of input fields, as below:

Step 5: Select ‘Text Input’. A text input field will appear in the editor. Rename it to “cookiename”. Note that the name you are assigning here will be used in coding the template functionality so do not use spaces in the name field.

Enter a Display Name: (Optional) Represents the label of the template field when rendered in the GTM UI. If missing, the field will not have a label (e.g. a checkbox field may not need a display name).

You can click on the settings icon to add additional fields. This will open an overlay with the different types of configuration settings which you can add to help users configure the custom template.

Let’s add help text and validation rules from the overlay:

Step 6: Help Text (Optional) gives informational text (rendered as a tooltip) to help the user enter a valid value into the template field. You can see the UI of the template in the template preview section and when you hover your mouse over the ‘Cookie Name’ it will pop up the help text like below:

Step 7: Now click on ‘Add rule’ to provide validation. Since we are creating a cookie in our custom template, cookie name is required therefore the user cannot keep it blank. We will add a validation rule that dictates ‘This value cannot be empty’:

Step 8: Let’s add a few more input fields with the configuration as below:

Cookie Value:

  • Field Type: Text input
  • Field Name: cookievalue
  • Display Name: Enter Cookie Value
  • Text Input Configuration: Toggle On “Always in summary”, “Display name” and “Validation rule”
  • Validation Rule: ‘This value cannot be empty’

Cookie Expiry Type:

  • Field Type: Drop Down Menu
  • Field Name: cookieexpiretype
  • Display Name: Cookie Expiry Time
  • Text Input Configuration: Toggle On “Always in Summary”, “Display Name” and “Default Value”
  • Drop-Down Menu Items:
    1. Item Name “Minute” and Item Value “minute”
    2. Item Name “Hour” and Item Value “hour”
    3. Item Name “Minute” and Item Value “minute”
    4. Item Name “Day” and Item Value “day”
    5. Item Name “Session” and Item Value “session”
  • Default Value: “session”

Group Minutes:

  • Field Type: Group
  • Field Name: group1expireminutes
  • Display Name: Set Expiry Minute
  • Group Style: Collapsible section –Open (Click on the drop-down under ‘Group style’ to select this option)
  • Collapsible Group Configuration: Toggle On “Display Name”, “Enabling Condition” and “Group Style”
  • Enabling Condition: “cookieexpiretype” equals “minute” (Click on add condition to set this)

Now in this group input field, we are going to add a nested field in order to create selectable drop-down items containing the ‘minute’ values. Click on ‘Add Field’ as shown in the above screenshot.

Nested Group Minutes:

  • Field Type: Drop Down Menu
  • Field Name: expiryminutes
  • Display Name: Minutes to Expire
  • Text Input Configuration: Toggle On “Display Name”
  • Drop-Down Menu Items:
    1. Item Name “10 Min” and Item Value “10”
    2. Item Name “30 Min” and Item Value “30”

You can add more values based on your requirements.

Group Hours:

  • Field Type: Group
  • Field Name: group1expirehours
  • Display Name: Set Expiry Hour
  • Group Style: Collapsible section –Open (Click on the drop-down under Group Style to select this option)
  • Collapsible Group Configuration: Toggle On “Display Name”, “Enabling Condition”, “Group Style”
  • Enabling Condition: “cookieexpiretype” equals “hour” (Click on add condition to set this)

Now in this group input field, we are going to add a nested field in order to create a selectable drop-down item containing the ‘hour’ value. Click on ‘Add Field’ as shown in the above screenshot.

Nested Group Hours:

  • Field Type: Drop Down Menu
  • Field Name: expiryhours
  • Display Name: Hours to Expire
  • Text Input Configuration: Toggle On “Display Name”
  • Drop-Down Menu Items:
    1. Item Name “1 Hour” and Item Value “1”
    2. Item Name “5 Hour” and Item Value “5”
    3. Item Name “10 Hour” and Item Value “10”
    4. Item Name “20 Hour” and Item Value “20”
    5. Item Name “23 Hour” and Item Value “23”

You can add more values based on your requirements.

Group Days:

  • Field Type: Group
  • Field Name: group1expiredays
  • Display Name: Set Expiry Day
  • Group Style: Collapsible section –Open (Click on the drop-down under Group Style to select this option)
  • Collapsible Group Configuration: Toggle On “Display Name”, “Enabling Condition”, “Group Style”
  • Enabling Condition: “cookieexpiretype” equals “day” (Click on add condition to set this)

Now in this group input field, we are going to add a nested field in order to create a selectable drop-down item containing the ‘day’ value. Click on ‘Add Field’ as shown in the above screenshot.

Nested Group Days:

  • Field Type: Drop-Down Menu
  • Field Name: expirydays
  • Display Name: Hours to Expire
  • Text Input Configuration: Toggle On “Display Name”
  • Drop Down Menu Items:
    1. Item Name “7 Day” and Item Value “7”
    2. Item Name “14 Day” and Item Value “14”
    3. Item Name “21 Day” and Item Value “21”
    4. Item Name “30 Day” and Item Value “30”

You can add more values based on your requirement.

Group Advance:

  • Field Type: Group
  • Field Name: group1advance
  • Display Name: Domain and Path Settings
  • Group Style: Collapsible section –Open (Click on the drop-down under Group Style to select this option)
  • Collapsible Group Configuration: Toggle On “Display Name” and “Group Style”

Now in this group input field, we are going to add a nested field in order to create text input fields to set domain name and path name for the cookie

Nested Text Input:

For Custom Domain (Optional)

    1. Field Type: Text Input
    2. Field Name: customdomain
    3. Display Name: Set Domain

For Custom Path (Optional)

    1. Field Type: Text Input
    2. Field Name: custompath
    3. Display Name: Set Path

Up until this point, we have added all the input fields required for creating an easy to configure user interface in GTM for custom template tag users. Your field window should look like below:

You can check its preview in the adjacent preview panel:

Click on ‘Save’ to save your first custom template.

But wait… is it done? Well not yet, we still need to add code and permissions to this template in order for it to work.

Step 9: Click on the ‘Code’ tab, just beside ‘Fields’ in the template editor. You will see a screen like below with some code already present. Don’t worry we will replace this code with ours in the next step.

Step 10: Add some code.

Before we add our code to the custom tag template, note that the code format used here is sandboxed JavaScript.

Sandboxed JavaScript is a simplified subset of the JavaScript language which provides a safe way to execute logic from Google Tag Manager’s Custom Tag Template. It offers a variety of template APIs which you can use in your template to access outside variables, like creating a cookie, sending pixel calls, accessing the dataLayer, etc.

Please paste the code below into your code. This will create a custom cookie in the browser with fields specified by users in the UI.

// Require the necessary APIs

const log = require(‘logToConsole’);

const setCookie = require(‘setCookie’);

const queryPermission = require(‘queryPermission’);

// define you field items here

const cookiename = data.cookiename;

const cookievalue = data.cookievalue;

const expiryminutes = data.expiryminutes;

const expiryhours = data.expiryhours;

const expirydays = data.expirydays;

const cookieexpiretype = data.cookieexpiretype;

const customdomain = data.customdomain;

const custompath = data.custompath;

//write function code

function expire(cookieexpiretype) {

if (cookieexpiretype === ‘minute’) {

return expiryminutes * 60;

} else if (cookieexpiretype === ‘hour’) {

return expiryhours * 3600;

} else if (cookieexpiretype === ‘day’) {

return expirydays * 86400;

}

}

const customparameter = {

‘domain’: customdomain,

‘path’: custompath,

‘max-age’: expire(cookieexpiretype),

};

log(customparameter);

//Set cookie

setCookie(cookiename, cookievalue, customparameter);

// Call data.gtmOnSuccess when the tag is finished.

data.gtmOnSuccess();

 

The ‘data’ object in the above code represents the field input type user will interact with and select.

The data.gtmOnSuccess() method indicates the success of the tag execution.

We will talk more about the code configuration in detail later on in this article.

Step 11: Click on ‘Permissions’ in the template editor to set the required permissions for the custom tag template.

You can see from the above image that there are two permissions already displayed. This is because we have used the following commands in the code window:

const log = require(‘logToConsole’);

const setCookie = require(‘setCookie’);

Permissions are automatically detected based on APIs used in the ‘Code’ tab. You can use the current tab to set limitations on the detected permissions

const log = require(‘logToConsole’);
this permission allows the user to log to the developer console and Tag Manager’s preview mode. There are two limitation types available here:

1) Only log during debug and preview

2) Always log

You can limit the logs by clicking the radio button like below:

const setCookie = require(‘setCookie’);
this permission sets the limitations to allow specific types of cookies only. Since we are creating a custom template for cookie creation you can describe here what type of cookies can be created.

You can add multiple types of cookies for the user. Just click on ‘+ Add allowed cookie’.

An overlay will appear on the right-hand side. Set the cookie name as “Campaign_ID” and click on ‘Add’.

This will allow the custom tag template only to write a cookie with the name of  ‘Campaign_ID’. If you create any other cookies, like “my_cookie” or “client_id”, the tag will not fire. You can always add the type of cookie you want to create in the permissions tab. Put ‘*’ in the ‘Domain’ field and ‘Path’ field so that they can contain any value. Leave the ‘Secure’ and ‘Session’ fields as ‘Any’.

Click on ‘Save’ and you are done.

Congratulations! You have successfully created your first custom tag template.

You can go to your ‘Tags’ tab and click on ‘New Tag’, then ‘Tag Configuration’. In the overlay that appears, you can see your custom tag template.

Click on it and you will get a screen like the one below, containing the UI of your custom tag template.

Variable template overview

Just like the custom tag template, GTM also has variable templates.

A variable template returns the value of the API call. You can use a custom variable template when you want to pass a particular value to a tag. Instead of custom JavaScript variables, you can use variable templates, which are more convenient to use.

In this variable template overview, I will show you step-by-step, the method for creating a custom variable template. In this overview, we are using the example of creating a custom variable template which returns the value of the GTM container version. Follow the steps below to create your tag template:

Step 1: Navigate to Google Tag Manager Console and click on ‘Templates’ in the left-hand side menu:

Step 2: Click on ‘New’ in the upper right-hand corner under ‘Variable Template’ and you will see an interface like the one below:

Step 3: Now fill in your variable template information in the ‘Info’ tab.

Name: The template name that will be presented to GTM users. This name will appear in many places such as the type picker in GTM UI.

Description: (Optional) A short description of the template.

Step 4: ‘Fields’ Tab: Some variables might need their fields to be described. In our case we just want to assign the GTM container details to the variable hence we will keep it blank.

Click on the ‘Code’ tab in the template editor and you will see an interface like the one below:

Step 5: Replace the code in the interface with the below code:

const getContainerVersion = require(‘getContainerVersion’);

return getContainerVersion();

The above code executes the getContainerVersion API and returns its value.

Step 6: Click on the ‘Permissions’ tab in the template editor. You will see that the ‘Reads container data’ permission will be automatically assigned, as below:

You don’t need to do anything here.

Step 7: Click on ‘Save’ in the upper right-hand corner.

You are done! Congratulations, you have created your first custom variable template. You can see your template preview like below:

Core coding concepts of custom templates

Sandboxed JavaScript

Custom templates use sandboxed JavaScript, which is a more simplified subset of the JavaScript language.

A few features of the normal JavaScript language have been removed in order to provide a safe and secure execution environment.

This new subset is deployed on ECMAScript 5.1. and has some ECMAScript 6 features. This supports arrow functions like “const” and “let”.

ECMAScript 6 Syntax

ES6 (ECMAScript 6) is very user-friendly and easy to use. In our case, I will only highlight the most used syntaxes.

1) Arrow function (ES6)

Arrow functions ()=>{} are great to use since they save us some time from typing function() {}, which is more technical and complex in nature. Also, it gives us a fine view while editing our code file.

Let’s take the example below, in this case, we want to log the output of the total number of days in the week when the number of visits is equal to three times per day.

const numberOfVisitCountThisWeekByDay = [3, 2, 2, 0, 2, 1, 3];

const checkNumberEqualsThree = num => num === 3;

const numberOfDaysWith3Visit = numberList => numberList.filter(checkNumberEqualsThree).length;

numberOfDaysWith3Visit(numberOfVisitThisWeek);

// output: 2

2) Default parameter values (ES6)

This is extremely handy if you want to call a function with and without arguments. We can use these parameter values in a custom variable which includes user input.

const SocialShare = (Activity = ‘Share to Facebook’) => {

console.log(‘I Like the blog ‘ I want to + Activity);

}

SocialShare();

// output: I Like the blog I want to Share to Facebook

SocialShare(‘Share to Twitter’);

// output: I Like the blog I want to Share to Twitter

Limitations and restrictions of sandboxed JavaScript

Google Tag Manager has come up with a multiple suppression mechanism to avoid users finding ways (with code and permissions) to break its sandbox environment.

A few examples are below:

  1. No access to “window.” and “document.” attributes.
  2. No access to DOM elements like GTM Variable {{Variable Name}}
  3. No custom events or non-plain objects like “dataLayer.push” which were used in earlier custom tags and variables.

In order to start coding, you need to know the APIs which are used in sandboxed JavaScript. For a complete list of APIs used in Google Tag Manager’s custom tag templates, you can visit Google’s developer  documentation

Fields and configuration details

Up until now, you have got an idea about how to create a custom tag template and custom variable template. We also talked about how the coding concept uses sandboxed JavaScript. Now let’s take a deep dive into the different field types available and when to use them.

When you click on ‘Fields’ in the template editor, you get multiple options of fields to add, like below

1. Text Input

Text input fields allow the user to input text. This may involve a string, or number or both. User can also assign a variable value to the textbox.

The below images show how textbox input looks in the template editor and in the actual tag UI:

With the textbox input field, you get additional settings that can be applied to it by clicking on the ‘Settings’ icon:

An overlay will appear showing available the field configuration settings, like below:

Allow Empty String: This setting is off by default. It is optional whether the field’s value can be an empty string.

If the checkbox is checked, the field’s value will be an empty string if the user does not enter any value in the GTM UI.

If unchecked, the field’s value will be undefined if a user does not enter any value in the GTM UI.

Always in Summary: This setting is optional. If true, the template field will always be visible in the GTM UI in summary view.

Clear on Copy: This is also an optional setting. If the checkbox is checked, this field’s value will be cleared if the user makes a copy of the tag or variable in Google Tag Manager. If unchecked, or not used, the field value will also be copied when the tag or variable is duplicated.

Default Value: This setting is optional. This sets the default value of the template field if not changed by the user. The same default value will also be used in the code.

Display Line Count: This is optional. It represents the number of lines the text field displays. If the value is missing or is 1, the text field will only accept a single-line string value.

Display Message: When Not Set: This is optional. It shows the text in the read-only view when the field is not set or kept empty.

Display Name: This is optional. This is the label of the template field when rendered in the GTM UI. If missing, the field will not have a label (e.g., a CHECKBOX field may not need a display name).

Enabling Condition: This setting is optional. This is used to decide if the current template field is enabled or not. If any of the conditions are met for other input fields, this field will be enabled.

This setting is always used with other input fields. Only if the conditions are met will the current field will be shown in GTM UI.

If the conditions are not met then the current field won’t be shown in the UI.

Help Text: This is an optional setting. You can provide users with informational text (rendered as a tooltip) to help the user enter a valid value into the template field. Enabling this will add a question mark in front of the display text. When a cursor hovers over the question mark, the text will be displayed in a small pop up.

Text as List: This is an optional setting. When enabled, multi-line inputs will be treated as a list of strings instead of a single string. You can only use this setting with the display line count setting.

Validation Rule: This is an optional setting. It creates a sequence of validation rules that can be applied to the field value when it is edited in the GTM UI. If any of the validation rules return false, GTM UI will show the errors and prevent the user from saving.

There are multiple validation rules available, as below:

Value Hint: This is an optional setting. You can use it to provide a hint to guide the users to enter a valid value.

Value Unit: This is an optional setting. You can use it to provide the value unit expected to guide the user into entering a valid value.

2. Drop-Down Menu

The drop-down menu field provides a menu list where only a single item can be selected. You can also add your global variables into the drop-down menu.

Available configuration settings with the drop-down menu are as follows:

  • “Not set” option
  • Always in summary
  • Clear on copy
  • Default value
  • Display name
  • Help text
  • Include variables
  • Nested fields
  • Validation rules
  • Value unit

Now let’s take a look at the extra configuration settings for the drop-down menu which we didn’t discuss earlier.

“Not set” option: This is an optional setting. This is the value shown in the SELECT when the field’s value is not set. If this field is not present, the drop-down menu will not include such a “blank” item.

Include Variable: This is an optional setting. If true, the selected drop-down will include the container’s variables in addition to the menu items specified in the select items.

Nested Fields: You can add nested fields inside the drop-down menu if you want to make it more customizable. Nested fields are dependent on enabling a condition of the parent input field type selected. You can add any of the field types in the nested field.

3. Checkbox

Checkbox fields are used when you want to return some value of true or false. No configuration settings are on by default for a checkbox.

You can always select below configuration settings for a checkbox

  • Always in summary
  • Clear on copy
  • Default value
  • Display name
  • Enabling conditions
  • Help text
  • Nested fields
  • Validation rules

4. Radio Buttons

A radio button is a graphical control element that allows the user to choose only one of a predefined set of mutually exclusive options. The selected option’s value will be available in the ‘Code’ tab.

Available configuration settings with radio button are

  • Clear on copy
  • Default value
  • Display name
  • Enabling conditions
  • Help text
  • Nested fields
  • Validation rules

5. Simple Table

With a simple table, you can allow a user to add and remove rows as per their requirements. You can give the option to add via text field or drop-down menus. In the ‘Code’ tab you will get the result as an array object. You can also specify its condition by adding some validation rules as well.

Available configuration settings with a simple table are

  • New row button text
  • Always in summary
  • Clear on copy
  • Default value
  • Display message when not set
  • Display name
  • Enabling conditions
  • Help text
  • Validation rules

New Row Button Text: You can toggle this on if you wish to give a descriptive name to a new row button. You can see in the above image instead of “Add Row” we have chosen the button text to be “Add Product”.

6. Param Table

A more complicated table input whose cells cannot be individually edited; instead, a row is the smallest unit for editing. You can select any input field from text input, drop-down, checkbox and radio button. In our case, we have selected radio button and text field. So, in the ‘Code’ tab we will get its output as {“CategorySelect”: “mens”, “ProductInput”: “Shoes”}.

The following screenshots show param table in the template editor, the UI showing how the user can add a product, and the tag template preview:

 

Available configuration settings with a param table are:

  • “Edit row” dialog title
  • “New row” button text
  • “New row” dialog title
  • Always in summary
  • Clear on copy
  • Default value
  • Display message when not set
  • Display name
  • Enabling conditions
  • Help text
  • Validation rules

“Edit row” dialog title: “Edit Row” is an available field in param table where users can add rows and edit as well. It’s very handy when you want to add a particular dimension in a tag template.

 

“New row” dialog title: The “New row” dialog title displays the text you see as the heading while adding a new row to the param table:

Permissions details

Permissions are automatically detected in sandboxed JavaScript based on what APIs are used. This happens as quickly as edits are made in the custom template code. Permissions are editable in the custom template editor; you can make the permission more specific by adding conditions.

Following are the permissions you can use in your custom tag template or custom variable template.

Accesses Global Variables:

Accesses Global Variables permission allows the code to read, write, and execute global variables.

If you want your code to access a global variable, you can add that global variable key using the access global variable permission and specify whether the code can read, write and execute global variable.

You can add a key by clicking on the ‘Add Key’ button and then an overlay will appear where you can specify its details:

Accesses Local Storage:

The access local storage permission allows the code to read and write to the local storage of the browser. You can use this by specifying the permissions for every key in local storage.

Reads Cookie Value(s):

Reads the values of the cookies with the specified name. You can select to allow the code to read any cookie or specific cookie by entering the cookie name in the “Allowed cookie names (one per line)”.

Reads Referrer URL:

The reads referrer URL permission allows template code to access the referring page URL. You set rules access to any combination of its URL parameters. There are several URL parameters as below

  • Protocol: http or https
  • Host: optimizesmart.com
  • Port: Web-browsers use the URL protocol prefix (http://) to determine the port number (http = 80, https = 443, ftp = 21, etc.)
  • Path: /blog/article5
  • Extension: HTML
  • Query: gclid=1.2.3.4

Reads URL:

Read URL also uses the same API as reads referrer URL. The only difference is that read URL accesses the current URL of the page while reads referrer URL accesses the previous page URL, the page from which the user has landed on the current page.

The reads URL permission allows template code to access the referring page URL. There are several URL parameters as below

  • Protocol: http or https
  • Host: optimizesmart.com
  • Port: Web-browsers use the URL protocol prefix (http://) to determine the port number (http = 80, https = 443, ftp = 21, etc.)
  • Path: /blog/article5
  • Extension: HTML
  • Fragment: contact-us
  • Query: gclid=1.2.3.4

Injects Hidden Iframes:

This permission allows the template code to inject hidden iframes into the website. This is very useful in case you want to set your own tracker on the website.

Each URL match pattern must use HTTPS and specify both host and path patterns. The host can be a domain like ‘optimizesmart.com’ or a specific subdomain like ‘blog. optimizesmart.com ‘, The path pattern must consist of ‘/’ followed by zero or more characters. An asterisk in the path pattern will be interpreted as a wildcard. A path with no trailing characters will be treated as a wildcard.

Injects Scripts:

This permission allows the template code to inject script on the page. This is very useful for injecting script like Facebook tracking. You can create your custom tag template for Facebook events as well.

Each URL match pattern must use HTTPS and specify both host and path patterns. The host can be a domain like ‘optimizesmart.com’ or a specific subdomain like ‘blog.optimizesmart.com ‘, The path pattern must consist of ‘/’ followed by zero or more characters. An asterisk in the path pattern will be interpreted as a wildcard. A path with no trailing characters will be treated as a wildcard.

Logs to Console:

This permission allows the template code to log to the developer console and Tag Manager’s preview mode. You can set this permission to log only in preview mode or always log.

Reads Data Layer:

This permission allows the template code to read DataLayer values. You can also use wildcard regex here to give access to the code to read all values under main DataLayer variable and their nested variables as well like ecommerce.*

Using this wildcard, the code will be able to read nested dataLayer variables as well, like “ecommerce.addtocart.product_name”, “ecommerce.addtocart.product_price”, “ecommerce.addtocart.product_quantity”, etc.

Reads Document Character Set:

This permission allows the template code to read the readCharacterSet API, which, returns the value of “document.characterSet”. Since it is a very simple permission, it does not require any rules to limit.

Reads Container Data:

This permission allows the template code to read use the getContainerVersion API and return its value.

Reads Event Metadata:

This permission allows the template code to use addEventCallback API. The addEventCallback API allows you to register a callback function that will be invoked at the end of an event.

Reads Document Title:

This permission allows the template code to use the readTitle API, which returns the value of document.title

Sends Pixels:

This permission allows the template code to send a GET request to a specified URL which accepts this request and store the data in custom web API. You can define your URL to match the pattern you added in the permissions tab.

Sets a Cookie Value:

This permission allows the template code to set a cookie value. You can set the limitations to allow specific types of cookies only. You can also configure the domain, path, secure (to set with a secure flag or not) and session (to set session-level cookie or any) parameters for cookie.

For more details on permissions visit Google’s developer documentation

Testing custom template

Unit tests for custom tag templates and custom variable templates help you verify the template’s functionality. For each custom template, you can build a set of tests that can be run without having to deploy your tag. This allows you to continuously test actions during development. This is very helpful to check whether the tags fire correctly or not. You can also check different contingencies for various scenarios in which a user might use the tag.

Follow the steps below to know more about how to test the custom template. In the below example we are going to add mock data to test a custom template variable which returns the lowercase sting for the provided value in a text box.

Step 1: Navigate to Google Tag Manager Console and click on ‘Templates’ in the left-hand side menu:

Step 2: Click on ‘New’ in the upper right-hand corner under ‘Variable Template’ and fill in your variable template information in the ‘Info’ tab, like below:

  • Name: Convert to Lower String
  • Description: (Optional) Converts the String in Lower Case

Step 3: Now go to the ‘Fields’ tab, click ‘Add Field’ and select ‘Text input’. Name the field ‘InputText’ and set the display name to ‘Enter a string to convert’.

Step 4: Click on the ‘Code’ tab in the template editor and replace the default code with below sandboxed JavaScript

let input = data.InputText;

return input.toLowerCase();

Step 5: Click on ‘Tests’ tab in the template editor and you will see an interface like below:

Run Tests: This button runs the test that you have defined. If there are multiple tests it will run all the tests.

Add Test: This button adds a single test to validate your template. You can add multiple tests as well if you want to check every piece of your code.

Documentation: Google developer documentation for carrying out tests

Step 6: Click on ‘Add Test’, change the test’s name from ‘Untitled test 1’ to ‘Strings Test’ and click on the expand icon ‘˅’ to reveal the test’s sandboxed JavaScript editor.

Step 7:  Replace the code in the editor with the following code and let’s try to understand the concept of ‘mocking the data object’ for running the test.

const mockData = {

// Mocked field values

InputText: ‘WWW.OPTIMIZESMART.COM’

};

// Call runCode to run the template’s code.

let variableResult = runCode(mockData);

// Verify that the variable returns a result.

assertThat(variableResult).isEqualTo(‘www.optimizesmart.com’);

 

  • In the above code “const mockData” is used to provide dummy data to the code since there will be no user interface to provide input to the data object. We run tests to debug the code and not the UI of the template.
  • InputText: is one key in the mockData object whose value is ‘WWW.OPTIMIZESMART.COM’
  • let variableResult = runCode(mockData); allows the test to run the template code using key in mockData as input.
  • “assertThat(variableResult).isEqualTo” validates the result (‘www.optimizesmart.com’); which is the lowercase version of the string.

This test passes the string ‘WWW.OPTIMIZESMART.COM’ to the variable and verifies that the variable returns the expected value of ‘www.optimizesmart.com’.

Step 8: Click on ‘Run Tests’ (runs all tests created) in the template editor. You can also run the individual test by clicking on arrow button in front of every test name in case you have multiple tests.

Step 9: Check the output of the test which will appear at the bottom of the console on the right-hand side.

As you can see from the screenshot below, our code has returned the original value of ‘WWW.OPTIMIZESMART.COM’ in lowercase to ‘www.optimizesmart.com’. You can also see the result as ‘Executed 1 test (SUCCESS)’.

If there are any errors in your code, you can see them in the console and make changes accordingly, in order to make it run properly. You can directly jump on the code line to inspect it in more detail by clicking on ‘Code tab’.

You can see in the above image, the console also tells you when the template preview started, test started, test logs and test result.

Running Code Template: If you want to see how your tag template runs, you can click on the ‘Run Code’ button available in template preview mode. Remember, here the code runs as it is available in the ‘Code’ tab and does not consider any data mocking like in the tests. If you have set any default values in the field settings, then this code will run with the default values.

Import, export and advanced settings

When you create a custom tag template or custom variable template there are multiple settings and options available, other than tag configuration.

Click on the three vertical dots near the ‘Save’ button above the template preview section to see the available settings.

Import: If you want to import a custom tag template or custom variable template you can click on ‘Import’. Note that Google Tag Manager uses the .tpl file format. TPL is a file extension for a template file format. A TPL file includes style data and other information required to create a specific document. Once you click on import it will open a file location window from where you can import the template.

One thing to consider while importing a file is that there is no option to directly import the template. You need to click on new template settings and then click on import. If you are already editing a template and then click on import feature, it will override the current template.

Export: To share a custom template within your organization, to other users and even if you want to use it in a different GTM container, you can export the template. It will create a template file in .tpl format and will be downloaded instantly. The name of your file will be your template name followed by the .tpl file extension, e.g. ‘My Custom Template.tpl’.

View Changes: If you have multiple versions available for a custom template this setting allows you to see the changes made compared to the newer version.

Copy: If you want to create a copy of your custom tag template or custom variable template you can select this settings option.

Delete: If you want to delete your custom template you can click on the delete option.

Show Advanced Settings: If you click on ‘Show Advanced Settings’, multiple configuration setting options will become available with a changed user interface in the template editor, as below

  1. A new ‘Notes’ option will be available in the template editor if you want to add notes to your tag template.
  2. The ‘Info’ tab and ‘Fields’ tab in the template editor will show a source toggle option which will give you the option to edit the settings in JSON format.

Show Test Page: The show test page Setting will add a test page section above the console in template preview mode. This is only useful if you want to check how the custom tag template made changes to your web page. You can also see errors in the page if something goes wrong.

Then there are two more settings available in case you want to interact with the Google community:

Send Feedback: You can send your feedback to Google along with a screenshot.

Help: A normal help section in case you want to read the documentation for custom templates, sandboxed JavaScript, API and permissions.

Template preview in Google Tag Manager preview mode

You can see your custom tag template and custom variable template in GTM preview mode as well, just like normal tag templates and variables. It will also give you details such as the different parameters you used in tag template, settings information, results like tag fired or failed.

Let’s check the custom tag template that we created for cookie creation:

You can also get the tag details by clicking on it:

Tag Type: The name we gave to the custom tag template.

Firing Status: Succeeded.

Enter Cookie Name: Field value where the user inputs the cookie name.

Cookie Expiry Time: Drop-down menu field user selected for cookie expiry time.

Set Domain: Optional setting we added to set cookie domain. Page Hostname is an inbuilt variable user assigned and will return its value with domain name.

Set Path: Optional setting we added to set cookie path. Page Path is variable inbuilt variable name user assigned and will return path name.

Hours to Expire: Nested drop-down field option selected by the user to 1 hour.

In the ‘Variables’ tab we can check the value for Page Hostname is “optimizesmart.com”, Page Path is “/aboutme” and Campaign ID is “Summer_Email_Campaign”:

We also have created a custom variable which returns the current timestamp in milliseconds. You can also check that in the ‘Variables’ tab, in preview mode.

Conclusion

Creating custom tag templates and custom variable templates in Google Tag Manager requires a lot of effort and coding skills. It’s not an everyday task and not compulsory as well.

It is up to you whether you want to use simple custom HTML tags or create custom tag templates. But for those having multiple GTM containers with lots of custom HTML templates, it’s worth going for custom tag templates.

Remember the following things are very important for any custom tag template and custom variable template.

  1. Custom tag templates and custom variable templates use sandboxed JavaScript.
  2. You have multiple input fields to create a great user interface for the end template user.
  3. Permissions are automatically detected from the code you write but you have the option to set rules for allowing specific permissions for custom tag templates.
  4. You can always test your code by adding mock data to the custom template.

Register for the FREE TRAINING...

"How to use Digital Analytics to generate floods of new Sales and Customers without spending years figuring everything out on your own."



Here’s what we’re going to cover in this training…

#1 Why digital analytics is the key to online business success.

​#2 The number 1 reason why most marketers are not able to scale their advertising and maximize sales.

#3 Why Google and Facebook ads don’t work for most businesses & how to make them work.

#4 ​Why you won’t get any competitive advantage in the marketplace just by knowing Google Analytics.

#5 The number 1 reason why conversion optimization is not working for your business.

#6 How to advertise on any marketing platform for FREE with an unlimited budget.

​#7 How to learn and master digital analytics and conversion optimization in record time.



   

My best selling books on Digital Analytics and Conversion Optimization

Maths and Stats for Web Analytics and Conversion Optimization
This expert guide will teach you how to leverage the knowledge of maths and statistics in order to accurately interpret data and take actions, which can quickly improve the bottom-line of your online business.

Master the Essentials of Email Marketing Analytics
This book focuses solely on the ‘analytics’ that power your email marketing optimization program and will help you dramatically reduce your cost per acquisition and increase marketing ROI by tracking the performance of the various KPIs and metrics used for email marketing.

Attribution Modelling in Google Analytics and Beyond
Attribution modelling is the process of determining the most effective marketing channels for investment. This book has been written to help you implement attribution modelling. It will teach you how to leverage the knowledge of attribution modelling in order to allocate marketing budget and understand buying behaviour.

Attribution Modelling in Google Ads and Facebook
This book has been written to help you implement attribution modelling in Google Ads (Google AdWords) and Facebook. It will teach you, how to leverage the knowledge of attribution modelling in order to understand the customer purchasing journey and determine the most effective marketing channels for investment.

Himanshu Sharma

Digital Marketing Consultant and Founder of Optimizesmart.com

Himanshu helps business owners and marketing professionals in generating more sales and ROI by fixing their website tracking issues, helping them understand their true customers' purchase journey and helping them determine the most effective marketing channels for investment.

He has over 12 years of experience in digital analytics and digital marketing.

He was nominated for the Digital Analytics Association's Awards for Excellence. The Digital Analytics Association is a world-renowned not-for-profit association that helps organisations overcome the challenges of data acquisition and application.

He is the author of four best-selling books on analytics and conversion optimization:

error: Alert: Content is protected !!