go-docxtemplate is a logic-aware DOCX template engine for Go. It generates Microsoft Word documents by merging JSON data with .docx templates.
go-docxtemplate preserves word styles, supports complex loops (tables & lists), nested templates (partials), conditional styling, and dynamic image injection.
- 📝 Formatting: Format numbers, currencies, and dates directly in Word (e.g.,
{{Price : #,##0.00 €}}). - 🔄 Logic & Loops: Full support for
{{if}},{{else}}, and{{foreach}}loops (tables and text). - 🖼️ Images: Inject Base64 images dynamically with resizing (
{{image Logo : 200 100}}). - 🧩 Nested Templates: Import other DOCX files (e.g., Headers/Footers) into the main document.
- ✂️ Conditional Removal: Remove entire table rows or paragraphs based on data (
{{remove_if IsEmpty}}).
go install github.com/dotwavehq/go-docxtemplate/cmd/cli@latestgo get install github.com/dotwavehq/go-docxtemplateGenerate a document by merging a template with JSON data and including a partial header.
go-docxtemplate \
-in template.docx \
-out invoice.docx \
-data payload.json \
-t Header=./templates/header.docx \
-del-l "{{" -del-r "}}"package main
import (
"github.com/dotwavehq/go-docxtemplate/pkg/docx"
"github.com/dotwavehq/go-docxtemplate/pkg/template"
)
func main() {
// 1. Open Template
reader, _ := docx.Open("template.docx")
defer reader.Close()
// 2. Prepare Writer & Engine
writer, _ := docx.FromReader(reader)
engine := template.NewEngine(template.DefaultConfig(), writer)
// 3. Register Partials (Optional)
engine.RegisterPartial("Header", "templates/header.docx")
// 4. Execute with Data
data := map[string]any{
"Customer": map[string]any{"Name": "ACME Corp"},
}
xmlContent, _ := engine.Execute(reader.GetDocumentXML(), data)
// 5. Save
writer.SetDocumentXML(xmlContent)
writer.WriteTo("output.docx")
}Values can be formatted using standard patterns (like Excel or Java).
Syntax JSON Data Result
{{Name}} "John" John
{{Price : #.##0,00}} 1250.5 1.250,50
{{Price : $ #,##0.00}} 1250.5 $ 1,250.50
{{Percent : 0 %}} 85 85 %
Control visibility of text.
{{if User.IsAdmin}}
ACCESS GRANTED
{{else}}
ACCESS DENIED
{{endif}}
Can be used in running text or inside Table Rows. If placed inside a table row, the row is duplicated for each item.
{{foreach Items}}
- {{Name}}: {{Price}}
{{endforeach}}
Removes the entire paragraph or table row if the condition is true.
{{remove_if Price == 0}}
Inject Base64 encoded images from your JSON.
Auto size: {{image Signature}}
Fixed size: {{image Logo : 300 100}} (Width Height in px)
Inject other DOCX files. Great for components like Headers or Terms & Conditions.
{{import Header}}
(Requires registering the alias Header via CLI -t Header=file.docx or engine.RegisterPartial()).
This project is licensed under the AGPL v3 License.