# Render Template

> Genera texto dinámico con el motor de plantillas Handlebars.

Source: https://docs.sommatic.ai/es/nodes/data.template/

- Slug: `data.template`
- Familia: Datos
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Genera texto dinámico con el motor de plantillas Handlebars.

Este operador permite combinar variables de datos con una plantilla de texto. Es ideal para construir correos, mensajes SMS, documentos HTML o consultas SQL.

**Características:**
- **Sintaxis Handlebars:** uso de `{{variable}}`, `{{#each list}}`, `{{#if condition}}`.
- **Entrada completa:** Acceso total al payload como contexto.

**Casos de uso:**
- Crear el cuerpo de un correo personalizado: "Hello {{user.name}}..."
- Construir una ruta de archivo compleja: "/archives/{{year}}/{{month}}/report.pdf"

## Configuración

- `template` (string, obligatorio): La plantilla de texto con sintaxis Handlebars.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Rendered
- `error`: Error

## Contrato de entrada

- `payload` (object, opcional): Contexto de datos disponible en la plantilla.

## Contrato de salida

- `result` (string, opcional): La cadena renderizada.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Render Template").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Render Template`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Render Template").item.json.result` (string): La cadena renderizada. **El worker no la devuelve: se lee como undefined.**
- `$("Render Template").item.json.customer` (object) = `{…}` (El editor no la sugiere)
- `$("Render Template").item.json.customer.name` (string) = `"Ana"` (El editor no la sugiere)
- `$("Render Template").item.json.order_id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("Render Template").item.json.text` (string) = `"Hello Ana, your order ord_123 is ready."` (El editor no la sugiere)


## Cómo funciona

Renderiza una plantilla Handlebars con el payload de entrada y agrega el texto resultante como `text`.

1. Lee `template` sin procesar desde la configuración: no pasa por el Expression Engine, así que todo `{{ }}` en ella pertenece a Handlebars. Las demás claves se resuelven como siempre.
2. La compila con Handlebars 4 y la renderiza con el payload como contexto: `{{customer.name}}`, `{{#each items}}...{{/each}}`, `{{#if paid}}...{{/if}}`.
3. Devuelve el payload más `text` por `out`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-ready-message",
  "label": "Ready message",
  "operator_slug": "data.template",
  "operator_version": "1.0.0",
  "config": {
    "template": "Hello {{customer.name}}, your order {{order_id}} is ready."
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "customer": {
      "name": "Ana"
    },
    "order_id": "ord_123",
    "text": "Hello Ana, your order ord_123 is ready."
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

La plantilla se renderizó.

```json
{
  "customer": {
    "name": "Ana"
  },
  "order_id": "ord_123",
  "text": "Hello Ana, your order ord_123 is ready."
}
```

### `error`

La plantilla tiene un error de sintaxis.

```json
{
  "ok": false,
  "errors": [
    "Template Error: Parse error on line 1: ..."
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `template`: Solo se ven los campos del payload. Las variables del Expression Engine (`$json`, `$("Node")`, `$now`, `$execution`) no existen aquí: escribe `{{order_id}}`, no `{{ $json.order_id }}`. Una plantilla vacía produce `""`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Template Error: Parse error on line <n>: <details>` | `error` | Sintaxis Handlebars no válida, como un bloque `{{#if}}` sin cerrar. |

## Notas y límites

- `{{ }}` escapa los caracteres HTML (`&`, `<`, `>`, comillas); usa `{{{ }}}` para salida sin escapar.
- Solo están los helpers integrados de Handlebars (`if`, `unless`, `each`, `with`, `lookup`, `log`); no se registran helpers propios. Los campos ausentes se muestran vacíos.
- La clave de salida es `text` (el contrato de salida dice `result`); una clave `text` existente se sobrescribe.
- Cuando el sobre no trae `data` (o `data` es falsy), el motor guarda el sobre completo como salida del nodo: por `error` el siguiente nodo recibe `{ ok: false, errors: [...], port: "error" }` como payload.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.template",
  "name": "Render Template",
  "category": "data",
  "version": "1.0.0",
  "description": "Generates dynamic text using the Handlebars templating engine.\n\n  This operator allows you to merge data variables into a text template. It is ideal for constructing emails, SMS messages, HTML documents, or SQL queries.\n\n  **Features:**\n  - **Handlebars Syntax:** usage of `{{variable}}`, `{{#each list}}`, `{{#if condition}}`.\n  - **Rich Input:** Full access to the payload as context.\n\n  **Use Cases:**\n  - Creating a personalized email body: \"Hello {{user.name}}...\"\n  - Constructing a complex file path: \"/archives/{{year}}/{{month}}/report.pdf\"",
  "capabilities": [
    "templating",
    "handlebars",
    "text-generation"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "template"
    ],
    "properties": {
      "template": {
        "type": "string",
        "title": "Template String",
        "format": "textarea",
        "description": "The text template using Handlebars syntax."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "payload": {
        "type": "object",
        "description": "Data context available in the template."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "string",
        "description": "The rendered string."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Rendered",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "handlebars",
    "html",
    "template",
    "text"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "template"
  ],
  "properties": {
    "template": {
      "type": "string",
      "title": "Template String",
      "format": "textarea",
      "description": "The text template using Handlebars syntax."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "payload": {
      "type": "object",
      "description": "Data context available in the template."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "string",
      "description": "The rendered string."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Rendered",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
