# Mail merge and templates

> Insert merge fields, write {{tokens}} with formatting filters, conditional sections and repeating rows, and merge customer data into documents with Birch UI Document Editor.

Templates contain placeholders that are replaced with data: a customer's name, an invoice total, a list of line items. Birch UI Document Editor supports two kinds that can be mixed in one document:

- **Merge fields** are inserted from the field menu and shown as chips such as «customer.name». They export to Word as `MERGEFIELD` fields, so the template also works with Word's own mail merge.
- **Tokens** are typed as plain text, such as `{{customer.name}}`. They are easy to write in Word or in the editor and support filters, conditions and repeating sections.

Offer your field names in the toolbar with the `mergeFields` option:

```ts
const editor = createDocumentEditor(host, {
  mergeFields: [
    { name: 'customer.name', label: 'Customer name' },
    { name: 'customer.address', label: 'Postal address' },
    { name: 'invoice.total', label: 'Invoice total' },
  ],
});
editor.insertField('customer.name');
editor.getFieldNames(); // every field and token the document uses
```

## Merging

```ts
const values = {
  customer: { name: 'Harper & Lowe LLP', address: '14 Fenwick Street\nLeeds LS1 4AP', tier: 'gold' },
  invoice: { number: 'INV-2026-0418', total: 18450.5, due: '2026-12-15' },
  lineItems: [
    { description: 'Contract review', hours: 12, rate: 420 },
    { description: 'Negotiation call', hours: 3.5, rate: 420 },
  ],
};

const merged = editor.merge(values, { locale: 'en-GB', currency: 'GBP' }); // a merged copy, the editor is unchanged
editor.applyMerge(values, { locale: 'en-GB' }); // replaces the editor content
```

`mergeDocument(data, values, options)` does the same without an editor, for example to generate letters on a server and save them with `documentToDocx`. Headers and footers are merged too. Each value takes the formatting of its placeholder, and line breaks in values become line breaks in the document.

`missing` controls placeholders without a value: `'empty'` (default) removes them, `'keep'` leaves the placeholder and `'placeholder'` writes `[customer.name]` so gaps are easy to spot in a preview.

## Tokens

A token may be split over several runs by formatting, which happens when part of it was made italic or when Word stored it in pieces (`{{custo` + *`mer.na`* + `me}}`). Such a token is merged as one, with the formatting of the run it starts in. `mergeFieldNames` finds it too.

| Token | Result |
| --- | --- |
| `{{customer.name}}` | A value by path. Array items use `items[0].name`. |
| `{{invoice.total \| currency}}` | £18,450.50 with `locale: 'en-GB', currency: 'GBP'`. `currency:"EUR"` picks a currency. |
| `{{invoice.total \| number:2}}` | 18,450.50 |
| `{{invoice.due \| date:"long"}}` | 15 December 2026. Styles: `short`, `medium` (default), `long`, `full`. |
| `{{discount \| percent}}` | 12.5% for `0.125` |
| `{{customer.name \| upper}}` | Also `lower`, `title` and `trim`. |
| `{{notes \| default:"None"}}` | A fallback for empty values. |
| `{{tags \| join:", "}}`, `{{lineItems \| count}}` | List helpers. |

### Conditions

`{{#if path}}…{{else}}…{{/if}}` keeps one of two parts; `{{#unless path}}` is the reverse. Empty strings, `0`, `false`, empty lists and empty objects count as false. Inside a paragraph the condition controls text; when the tags stand alone in their own paragraphs, they control the paragraphs between them:

```text
{{#if customer.tier}}
Your account manager will contact you within one business day.
{{/if}}
```

### Repeating sections and table rows

`{{#each path}}…{{/each}}` repeats its content for every item in a list. Inside, fields resolve against the item first and then the surrounding data, and `{{@number}}` and `{{@index}}` give the position.

To repeat **table rows**, put `{{#each lineItems}}` in the first cell of the row and `{{/each}}` in its last cell. The markers are removed and the row is repeated once per item, keeping its formatting; an empty list removes the row.

| Description | Hours | Amount |
| --- | --- | --- |
| `{{#each lineItems}}{{description}}` | `{{hours}}` | `{{rate \| currency}}{{/each}}` |

The same works for list items and whole paragraphs. Unbalanced tags are left in the text so mistakes are visible.

## Previewing records

Pass the records to merge as `mergeRecords` and the **Mail merge** group of the References tab shows **Preview results** with a record navigator. While the preview is on, the editor shows the template merged with one record and is read-only; turning it off puts the template back.

```ts
const editor = createDocumentEditor(host, {
  mergeRecords: [
    { customer: { name: 'Harper & Lowe LLP' }, invoice: { total: 18450.5 } },
    { customer: { name: 'Northwind Traders Ltd' }, invoice: { total: 6200 } },
  ],
});
editor.exec('mergePreview', true); // show the first record
editor.exec('mergePreview', { step: 1 }); // next record, wraps around; -1 goes back
editor.exec('mergePreview', { index: 1 }); // jump to a record (from 0)
editor.exec('mergePreview', false); // back to the template
```

The command returns `false` without records. The preview uses the default merge options; call `merge(values, options)` when you need a locale or a currency.
