Cómo crear una variable personalizada
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta guía, se explica cómo crear una plantilla de variable personalizada. Cuándo
se usa esta variable, tomará un array de valores y los mostrará como un
una cadena delimitada por comas.
Para comenzar con tu primera plantilla de variables, haz clic en Plantillas a la izquierda.
y haz clic en el botón New en Variable Templates
sección.
En la pestaña Info, define el Name y la Description de la variable.
El nombre es el que se les presentará a los usuarios cuando implementen esto.
en toda la interfaz de usuario de Tag Manager.
Una descripción es justo lo que parece: un resumen (de 200 caracteres o
menos) descripción de lo que hace esta variable.
Haz clic en Actualizar para obtener una vista previa de tu plantilla.
A la derecha de las entradas del campo, hay la ventana Template Preview.
Cada vez que se realice un cambio en el editor, el botón Actualizar
para que aparezca la opción. Haz clic en Actualizar para ver qué efecto tienen tus cambios en el aspecto de tu
de salida.
Haz clic en Campos para agregar campos a tu plantilla de variables.
La pestaña Campos del Editor de plantillas te permite crear y editar campos en la
plantilla de variables. Los campos se utilizan para ingresar datos personalizados, como una cuenta.
ID. Puedes agregar los elementos estándares del formulario, como campos de texto, menús
menús, botones de selección y casillas de verificación.
Haz clic en Agregar campo y selecciona Tabla simple. Reemplaza el nombre predeterminado (p.ej.,
"simpleTable1") con "list". En Vista previa de la plantilla, haz clic en Actualizar.
Repite este paso para una Entrada de texto y nómbrala "array", con dos Checkboxes.
llamado "use_array" y "sort", y una entrada de texto llamada "{delimitador".
En "delimitador", asígnale un valor predeterminado de ""," haciendo clic en el ícono de ajustes,
activando "Valor predeterminado" y completa el nuevo Valor predeterminado.
campo de entrada.
Haz clic en la pestaña Code y, luego, ingresa JavaScript de zona de pruebas en el editor:
var input = data.array;
if (!data.use_array) {
input = [];
for (var i = 0; i < data.list.length; i++) {
input.push(data.list[i].values);
}
}
if (data.sort) {
input.sort();
}
return input.join(data.delimiter || ',');
El código para esta variable es bastante sencillo, pero hay algunos
lo que vale la pena señalar.
data
.
Hay algunos campos a los que se accede desde el data
global.
data
contendrá los valores que configuraste en el paso anterior.
Por eso, podemos acceder a data.use_array
, data.sort
,
data.list
y data.delimiter
.
delimiter
se establece en un valor predeterminado de ","
si data.delimiter
es
no proporcionado. Es una buena práctica establecer valores predeterminados para un campo si
uno tiene sentido. Esto facilita el uso de la variable
plantilla, ya que no tiene que completar todos los campos para usar
la variable.
Haz clic en Guardar para guardar el progreso. Se cargarán los permisos detectados
en el Editor de plantillas.
Algunas APIs de plantillas tienen permisos asociados que determinan qué
pueden o no pueden hacer. Cuando usas una API de plantilla, como sendPixel
, en
tu código, Tag Manager mostrará los permisos relevantes en la sección Permisos
.
En la pestaña Vista previa de la plantilla, agrega algunos valores para los "valores". entrada, haz clic
Ejecuta el código y consulta la consola para ver el resultado de la variable.
Si hay algún error, aparecerá en la ventana de la consola.
Haz clic en Guardar y cierra el Editor de plantillas.
La plantilla de variables ya debería estar lista para usarse.
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-07-25 (UTC)
[null,null,["Última actualización: 2025-07-25 (UTC)"],[[["\u003cp\u003eThis guide provides step-by-step instructions to create a custom variable template in Google Tag Manager.\u003c/p\u003e\n"],["\u003cp\u003eThis template transforms an array of values into a comma-separated string using JavaScript code within the template.\u003c/p\u003e\n"],["\u003cp\u003eThe template utilizes fields like 'list', 'array', 'use_array', 'sort', and 'delimiter' to customize its functionality.\u003c/p\u003e\n"],["\u003cp\u003eUsers can preview and test the template using the 'Template Preview' and 'Console' sections within the editor.\u003c/p\u003e\n"],["\u003cp\u003eOnce saved, the custom variable template is ready to be implemented within Google Tag Manager.\u003c/p\u003e\n"]]],["To create a variable template that returns a comma-delimited string from an array, start by creating a new template, defining its name and description in the *Info* tab. Then, in the *Fields* tab, add fields for a simple table (\"list\"), text input (\"array\"), checkboxes (\"use_array\", \"sort\"), and text input (\"delimiter\"). In the *Code* tab, enter sandboxed JavaScript to process these fields, joining the array with the specified delimiter, and save. Then preview the result and save the variable.\n"],null,["# Create a custom variable\n\nThis guide will walk you through how to create a custom variable template. When\nthis variable is used, it will take an array of values and return them as a\ncomma delimited string.\n\n1. To begin your first variable template, click Templates in the left\n navigation and click the *New* button under the *Variable Templates*\n section.\n\n2. In the *Info* tab, define the variable's *Name* and *Description*.\n\n **Name** is what will be presented to users when they go to implement this\n variable throughout the Tag Manager user interface.\n\n **Description** is just what it sounds like - a brief (200 characters or\n less) description of what this variable does.\n3. Click *Refresh* to preview your template.\n\n To the right of the field inputs, there is a *Template Preview* window.\n Every time a change is made in the editor, the **Refresh** button will\n appear. Click Refresh to see what your changes do to the appearance of your\n variable.\n4. Click *Fields* to add fields to your variable template.\n\n The Template Editor's **Fields** tab lets you create and edit fields in the\n variable template. Fields are used to enter custom data, such as an account\n ID. You can add the standard form elements like text fields, drop down\n menus, radio buttons, and checkboxes.\n5. Click *Add Field* and select *Simple table* . Replace the default name (e.g.\n *\"simpleTable1\"* ) with *\"list\"* . In the *Template Preview* , click *Refresh*.\n\n Repeat this step for a *Text Input* and call it *\"array\"* , two *Checkboxes*\n called \"*use_array* \" and *\"sort\"* , and a *Text Input* called *\"delimiter\"* .\n For *\"delimiter\"* , give it a default value of \",\" by clicking the gear icon,\n toggling *\"Default value\"* to on, and then filling in the new Default Value\n input field.\n6. Click the *Code* tab and enter sandboxed JavaScript in the editor:\n\n var input = data.array;\n\n if (!data.use_array) {\n input = [];\n for (var i = 0; i \u003c data.list.length; i++) {\n input.push(data.list[i].values);\n }\n }\n\n if (data.sort) {\n input.sort();\n }\n\n return input.join(data.delimiter || ',');\n\n The code for this variable is fairly straightforward, but there are a few\n things worth pointing out.\n - `data` fields.\n\n There are a few fields that are being accessed off of the `data` global.\n `data` will contain the values that you set up in the previous step.\n That's why we're able to access `data.use_array`, `data.sort`,\n `data.list`, and `data.delimiter`.\n - `delimiter` is set to a default value of `\",\"` if `data.delimiter` is\n not provided. It's a good practice to set default values for a field if\n one makes sense. This makes it easier for users to use the variable\n template, since they don't have to fill out every field in order to use\n the variable.\n\n7. Click *Save* to save your progress. This will load any detected permissions\n into the Template Editor.\n\n Some Template APIs have [permissions](/tag-platform/tag-manager/templates/permissions) associated with them that dictate what\n they can or cannot do. When you use a template API such as `sendPixel` in\n your code, Tag Manager will show relevant permissions in the **Permissions**\n tab.\n8. In the *Template Preview* tab, add some values for the \"values\" input, click\n **Run Code** , and look at the *Console* to see the output for your variable.\n\n If there are any errors, they will appear in the **Console** window.\n9. Click *Save*, and close the Template Editor\n\n The variable template should now be ready for use."]]