# Render Template

> 使用 Handlebars 模板引擎生成动态文本。

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

- 标识: `data.template`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

使用 Handlebars 模板引擎生成动态文本。

该算子将数据变量合并到文本模板中，非常适合构建邮件、短信、HTML 文档或 SQL 查询。

**功能特性：**
- **Handlebars 语法：** 使用 `{{variable}}`、`{{#each list}}`、`{{#if condition}}`。
- **丰富的输入：** 可将整个载荷作为上下文完整访问。

**适用场景：**
- 生成个性化邮件正文：“Hello {{user.name}}...”
- 构建复杂的文件路径：“/archives/{{year}}/{{month}}/report.pdf”

## 配置

- `template` (string, 必填): 使用 Handlebars 语法的文本模板。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): Rendered
- `error`: Error

## 输入契约

- `payload` (object, 可选): 模板中可用的数据上下文。

## 输出契约

- `result` (string, 可选): 渲染后的字符串。

## 在表达式中

后续节点可通过 `$("Render Template").item.json.<路径>` 读取此节点输出中的内容（请把 `Render Template` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Render Template").item.json.result` (string): 渲染后的字符串。 **worker 不返回：读取结果为 undefined.**
- `$("Render Template").item.json.customer` (object) = `{…}` (编辑器不提示)
- `$("Render Template").item.json.customer.name` (string) = `"Ana"` (编辑器不提示)
- `$("Render Template").item.json.order_id` (string) = `"ord_123"` (编辑器不提示)
- `$("Render Template").item.json.text` (string) = `"Hello Ana, your order ord_123 is ready."` (编辑器不提示)


## 工作原理

使用输入 payload 渲染 Handlebars 模板，并将结果文本以 `text` 添加到 payload。

1. 从配置中原样读取 `template`：它不经过 Expression Engine，因此其中所有 `{{ }}` 都属于 Handlebars。其他配置键照常解析。
2. 用 Handlebars 4 编译，并以 payload 为上下文渲染：`{{customer.name}}`、`{{#each items}}...{{/each}}`、`{{#if paid}}...{{/if}}`。
3. 通过 `out` 返回 payload 加上 `text`。

## 在工作流中

### 节点

```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"
}
```

## 输出端口 (代码中的行为)

### `out`

模板渲染完成。

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

### `error`

模板存在语法错误。

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

## 代码中的行为

- `template`: 只能访问 payload 字段。Expression Engine 变量（`$json`、`$("Node")`、`$now`、`$execution`）在此不可用：请写 `{{order_id}}`，而不是 `{{ $json.order_id }}`。空模板渲染为 `""`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Template Error: Parse error on line <n>: <details>` | `error` | Handlebars 语法无效，例如 `{{#if}}` 块未闭合。 |

## 说明与限制

- `{{ }}` 会转义 HTML 字符（`&`、`<`、`>`、引号）；需要原样输出时请用 `{{{ }}}`。
- 只提供 Handlebars 内置 helper（`if`、`unless`、`each`、`with`、`lookup`、`log`）；未注册自定义 helper。缺失字段渲染为空文本。
- 输出键为 `text`（输出契约写的是 `result`）；已有的 `text` 键会被覆盖。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（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"
  }
]
```
