Skip to content
Templates and Mail Merge

Templates and Mail Merge

“Template” means two different things in these guides. One is a .docx you open for its styles, headers and numbering and then write fresh content into, which is what document.OpenTemplate gives you. The other is a .docx whose layout and wording are already final and which carries marked slots your program fills in. The two combine, but the calls involved have nothing to do with each other.

For the second kind, what differs between documents is how the slots are marked, and that choice belongs to whoever built the template rather than to the code filling it.

MarkerFilled withReaches headers and footersSurvives editing in Word
Merge fieldsdoc.MailMerge(map[string]string)YesYes. Word tracks them as fields.
{{PLACEHOLDER}} stringsYour own walk over doc.Paragraphs()NoPartly. See below.
Content controlsdoc.StructuredDocumentTags(), matched by Tag()YesYes, and they can be locked.

Merge fields are the most capable of the three. MailMerge finds them in body paragraphs, table cells, headers and footers, applies the field’s own formatting switches to your value, and clears the document’s mail merge settings on the way out so the saved file does not prompt to reconnect to a data source.

Placeholder strings are the easiest to produce and the most fragile to consume. Word is free to split {{TITLE}} across several runs, and it does so routinely after an edit, with no visible difference in the document. The Replace Placeholders example handles that up to a point: it accumulates text across the runs of a paragraph, so it still recognizes a placeholder whose braces and name land in different runs. What it cannot do is substitute one whose name is itself split, because the replacement is a per-run strings.ReplaceAll. Nothing warns you; the braces come off and the placeholder name is left in the document as ordinary text.

Content controls sidestep the whole problem, since Word stores them as objects with a tag rather than as text you have to find. If you own the template as well as the code, that is the mechanism to build it around. Placeholders are for the case where somebody hands you a document you do not control.

Where to look

GuideCovers
Use a TemplateOpening a document for its styles and writing new content in them.
Template with a HeaderReattaching a template’s header and footer after the body is cleared.
Replace PlaceholdersSubstituting {{NAME}} markers, and where the substitution misses.
Mail MergeWord merge fields, formatting switches and the merge settings.
Last updated on