coffee

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 21 Imported by: 0

README

coffee-templater for Go

Templating engine for Word (.docx), Excel (.xlsx) and PowerPoint (.pptx), plus a document model to parse Office files and build them back.

Powered by coffee-templater-engine, a Rust core compiled to WebAssembly. The engine is embedded in this module and runs on the pure-Go wazero runtime: no cgo and no files to ship. It is the same engine as in coffee-templater.js, so a document rendered from Go is byte for byte identical to the same document rendered from Node.js.

  • Variables, loops, conditions, else, filters, images
  • Configurable delimiters ({{x}}, ${x}, [[x]], …) and tag syntax
  • Tags split by Word into several runs ({{na + me}}) are handled transparently
  • Loops repeat inline text, paragraphs, table rows (Word, PowerPoint) or sheet rows (Excel)
  • Excel: numbers stay numbers, rows below a loop shift, formulas and merged cells follow
  • Custom filters written in Go
  • Inspect lists the variables of a template and returns a sample data shape
  • Parse → Go structs → Build: edit documents without losing formatting
  • Safe for untrusted uploads: limits against zip bombs, deep XML and runaway loops
  • Safe for concurrent use: a pool of engine instances; cancelling a context interrupts a render
go get github.com/vitJR1/coffee-templater.go

Requires Go 1.23 or later. A detailed guide in Russian is in DOCS.md.

Quick start

import coffee "github.com/vitJR1/coffee-templater.go"

templater := coffee.New(coffee.Options{})

template, _ := os.ReadFile("invoice.docx")
doc, err := templater.Render(ctx, template, map[string]any{
	"number": 42,
	"client": map[string]any{"name": "Ivan Petrov"},
	"items": []map[string]any{
		{"name": "Coffee", "qty": 2, "price": 10.5},
		{"name": "Tea", "qty": 1, "price": 4},
	},
	"paid": false,
})
if err != nil {
	return err
}
os.WriteFile("invoice-42.docx", doc, 0o644)

The same call works for .xlsx and .pptx: the format is detected from the file.

Compile once and render many times. A *Template is safe for concurrent use:

tpl, err := templater.Compile(ctx, template)
if err != nil {
	return err
}
defer tpl.Close()

for _, inv := range invoices {
	doc, err := tpl.Render(ctx, inv)
	// …
}

Template syntax

Syntax Meaning
{{name}} variable
{{client.address.city}}, {{items[0].name}}, {{map["key with spaces"]}} paths
{{price | number: 2}} filter with arguments
{{#items}}…{{/items}} loop over an array, enter an object, or render when truthy
{{#each items}}…{{/each}} explicit loop (arrays and objects, @key for objects)
{{#if paid}}…{{else}}…{{/if}} condition
{{#unless paid}}…{{/unless}} negative condition
{{^items}}…{{/items}} inverted section: rendered when the value is empty or falsy
{{/}} closes the innermost section
{{%logo}} image
\{{text}} literal {{text}}

Inside loops: @index, @number (1-based), @first, @last, @length, @key; . / this is the current item and ../name reaches the outer scope.

Built-in filters: upper lower capitalize trim replace truncate prepend append default, number fixed round currency percent date, join length first last reverse sort where slice json, eq ne gt gte lt lte not empty and or contains yesno.

The complete reference (placement rules for loops, every filter, Excel specifics) is in the engine's DOCS.md.

Data

Data is converted the way encoding/json does it: structs with their json tags (omitempty, omitzero, -, embedded structs), maps, slices, json.Marshaler and encoding.TextMarshaler. On top of that:

Go value In the template
time.Time a date: an absolute instant printed in UTC, or wall-clock time in Options.TimeZone
coffee.Date("2024-05-17") a naive date, printed as written (as in Excel)
coffee.Decimal("1234.50") an exact decimal; number, fixed, round and currency round it exactly
*big.Int, json.Number a number without precision loss
*big.Float, *big.Rat an exact decimal
[]byte binary data, sent to the engine as is (not base64)
coffee.Image{…} an image for {{%tag}}

Map keys are sorted, so the same data always gives the same document.

type Item struct {
	Name  string         `json:"name"`
	Price coffee.Decimal `json:"price"`
}

data := struct {
	Date  time.Time     `json:"date"`
	Items []Item        `json:"items"`
	Logo  *coffee.Image `json:"logo"` // nil removes the image tag
}{
	Date:  time.Now(),
	Items: []Item{{"Coffee", "10.50"}},
	Logo:  &coffee.Image{Data: png, Width: 120}, // pixels at 96 dpi; height follows the aspect ratio
}

Images: PNG, JPEG, GIF, BMP and SVG are detected from the bytes; other formats (webp, tiff, emf, …) need Extension. In Word the picture is inline at the tag. In PowerPoint the tag must be the only content of a text box, which is replaced by the picture fitted into it. Excel has no image tags yet.

Options

coffee.New(coffee.Options{
	Delimiters: coffee.Delimiters{Start: "${", End: "}"}, // default {{ }}
	EscapeChar: `\`,                                      // NoEscape: true disables escaping
	Syntax:     coffee.Syntax{Section: "@", Else: "otherwise"},
	Strict:     true,                    // missing values fail with ErrMissingValue
	NullValue:  coffee.NullValue{Mode: coffee.NullText, Text: "—"},
	DateFormat: "DD.MM.YYYY",            // default format of dates printed without a filter
	TimeZone:   moscow,                  // *time.Location for time.Time values
	Limits:     coffee.Limits{MaxLoopIterations: 10_000},
})

NullValue.Mode is NullEmpty (default), NullText, NullKeep (print the original tag) or NullError; NullValue.Func decides per tag instead. Stringify converts every non-string value to text. NoLinebreaks keeps \n in values instead of turning it into a line break.

Custom filters

templater := coffee.New(coffee.Options{
	Filters: map[string]coffee.Filter{
		// {{ total | money: "RUB" }}
		"money": func(value any, args ...any) (any, error) {
			amount, ok := value.(float64)
			if !ok {
				return nil, fmt.Errorf("money: %v is not a number", value)
			}
			return fmt.Sprintf("%.2f %v", amount, args[0]), nil
		},
	},
})

Filters receive values as map[string]any, []any, float64, string, bool, nil, coffee.Date, coffee.Decimal and []byte, and may return any value that could appear in data, so they work in conditions and loops too: {{#each items | onlyActive}}. A filter with the name of a built-in one replaces it. An error or a panic fails the render with ErrFilterFailed, and the message is in Details["hostMessage"].

A filter must not render with the same Engine while all of its instances are busy: a render that waits for a free instance inside a filter would wait forever.

Errors

The engine reports *coffee.Error. Compilation reports every mistake in the template at once:

tpl, err := templater.Compile(ctx, template)
var e *coffee.Error
if errors.As(err, &e) {
	for _, p := range e.Problems {
		fmt.Println(p.Code, p.Tag, p.Part) // unclosed_section {{#items}} word/document.xml
	}
}
if errors.Is(err, coffee.ErrUnknownFilter) { … } // matches any of the problems

Template codes: ErrUnclosedTag, ErrUnopenedTag, ErrUnclosedSection, ErrUnmatchedClose, ErrInvalidExpression, ErrUnknownFilter, ErrFilterFailed, ErrMissingValue, ErrInvalidSection, ErrInvalidImage, ErrUnsupported. Engine codes: ErrInvalidRequest, ErrInvalidOptions, ErrInvalidDocument, ErrUnsupportedFormat, ErrInvalidModel, ErrUnknownTemplate, ErrLimitExceeded, ErrHostError, ErrInternal.

A cancelled or expired ctx returns ctx.Err().

Inspecting templates

res, err := templater.Inspect(ctx, template)
res.Variables // [number client.name items[].name items[].price paid logo …]
res.Schema    // map[client:map[name:] items:[map[name: price:]] paid:true logo:<nil>]
res.Tags      // the tag tree: variables, images and sections with their children

Use it to build input forms or to validate data before rendering.

Document model

Parse turns a file into Go structs; edit them and Build the file back, passing the original file as the base. Everything the model does not cover (styles, images, fields, and so on) is kept as raw XML, and fields are written back only when they change, so a round trip keeps the formatting.

model, err := coffee.Parse(ctx, docx)
for i, block := range model.Parts[0].Blocks {
	if block.Type == "paragraph" {
		for j := range block.Children {
			run := &model.Parts[0].Blocks[i].Children[j]
			if run.Type == "run" {
				run.Text = strings.ReplaceAll(run.Text, "ACME", "Coffee Ltd")
				run.Bold = coffee.Ptr(true)
			}
		}
	}
}
out, err := coffee.Build(ctx, model, docx)
  • Word: Parts (body, headers, footers) → blocks (paragraphs, tables, raw) → inlines (runs, breaks, hyperlinks, raw).
  • Excel: Sheets → rows → cells with Value (string, float64, bool), Formula, Style, Type ("date", "error"). Sheets can be renamed, reordered, removed and created. Helpers: SheetToArrays, SheetToObjects, SheetFromArrays, ParseRef, ColumnToIndex, IndexToColumn, SerialToDate, DateToSerial.
  • PowerPoint: Slides → shapes (text, table, picture, …) → paragraphs → runs, plus speaker notes. Slides can be reordered and removed. A base file is required.

The base may be nil for docx and xlsx, so a document can also be built from scratch:

sheet := coffee.SheetFromArrays("Prices", [][]any{{"Name", "Price"}, {"Coffee", 10.5}})
xlsx, err := coffee.Build(ctx, &coffee.Document{Format: coffee.Xlsx, Sheets: []coffee.XlsxSheet{sheet}}, nil)

ExtractText returns the plain text of a file and DetectFormat its format.

Engine, concurrency and performance

An engine instance is single-threaded, so the package keeps a pool of instances: at most GOMAXPROCS operations run in parallel by default. A Template compiles itself lazily on each instance it runs on. Startup compiles the WebAssembly engine to machine code once per process (about 0.3 s); pass CacheDir to keep the compiled code on disk between runs.

engine, err := coffee.NewEngine(ctx, coffee.EngineConfig{
	MaxInstances: 4,                      // default runtime.GOMAXPROCS(0)
	CacheDir:     "/var/cache/coffee",    // optional compilation cache
})
defer engine.Close(ctx)

templater := coffee.New(coffee.Options{Engine: engine})
model, err := engine.Parse(ctx, doc)

Without Options.Engine, DefaultEngine() is created on first use.

Cancelling the ctx of a running operation interrupts the engine; that instance is dropped and a new one replaces it.

Limits

Input is treated as untrusted. Defaults: 100 MiB input, 10 000 zip entries, 500 MiB uncompressed, compression ratio 200, XML depth 256, 500 MiB output, 1 000 000 loop iterations and 1 000 000 filter calls per render. Zero keeps a default; coffee.Unlimited removes a limit.

coffee.New(coffee.Options{Limits: coffee.Limits{MaxInputBytes: 10 << 20, MaxLoopIterations: 10_000}})
coffee.Parse(ctx, upload, coffee.Limits{MaxEntries: 1000})

DTDs and external entities are never expanded; zip entries with unsafe paths are rejected.

Development

go test ./...                     # unit tests and the engine's conformance suite
scripts/update-engine.sh 0.1.3    # embed another engine release (checks its sha256)
scripts/update-engine.sh --local ../coffee-templater-engine/dist/coffee_core.wasm

testdata/conformance is a copy of the engine's language-independent conformance suite. Every case runs through the public Go API, and the sha256 of each rendered document must equal the one produced by the engine's Rust and JavaScript runners.

License

MIT

Documentation

Overview

Package coffee is a templating engine for Word (.docx), Excel (.xlsx) and PowerPoint (.pptx) files, plus a document model to parse Office files and build them back.

It runs coffee-templater-engine, a Rust core compiled to WebAssembly and embedded in this package, with the pure-Go wazero runtime: no cgo, no external files. The same engine backs the JavaScript library, so documents render byte for byte the same everywhere.

Templates are ordinary Office files with tags in the text:

Invoice {{number}} for {{client.name}}
{{#items}}- {{name}}: {{price | number: 2}}{{/items}}
{{#if paid}}Paid{{else}}Due{{/if}}
{{%logo}}

Render a template once:

doc, err := coffee.New(coffee.Options{}).Render(ctx, template, data)

or compile it once and render it many times (safe for concurrent use):

tpl, err := coffee.New(coffee.Options{}).Compile(ctx, template)
defer tpl.Close()
doc, err := tpl.Render(ctx, data)

Data is converted like encoding/json does (struct tags included), plus time.Time and Date for dates, Decimal for exact decimals, []byte for binary data and Image for image tags.

Errors from the engine are *Error values with a code that works with errors.Is:

if errors.Is(err, coffee.ErrUnclosedSection) { … }

See https://github.com/vitJR1/coffee-templater-engine/blob/main/DOCS.md for the template language, filters and the document model.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"strings"

	coffee "github.com/vitJR1/coffee-templater.go"
)

func main() {
	ctx := context.Background()
	template, _ := os.ReadFile("testdata/conformance/fixtures/invoice.docx")

	type Item struct {
		Name  string         `json:"name"`
		Qty   int            `json:"qty"`
		Price coffee.Decimal `json:"price"`
	}
	data := map[string]any{
		"number": 42,
		"client": map[string]any{"name": "Ann"},
		"items":  []Item{{"Coffee", 2, "10.50"}, {"Tea", 1, "4"}},
		"paid":   true,
	}

	templater := coffee.New(coffee.Options{
		Filters: map[string]coffee.Filter{
			"upper": func(v any, _ ...any) (any, error) { return strings.ToUpper(fmt.Sprint(v)), nil },
		},
	})
	doc, err := templater.Render(ctx, template, data)
	if err != nil {
		panic(err)
	}
	text, _ := coffee.ExtractText(ctx, doc)
	fmt.Println(strings.Split(text, "\n")[0])
}
Output:
Invoice 42

Index

Examples

Constants

View Source
const EngineSHA256 = wasm.SHA256

EngineSHA256 is the sha256 of the embedded coffee_core.wasm.

View Source
const EngineVersion = wasm.Version

EngineVersion is the version of the embedded coffee-templater-engine.

View Source
const ModelVersion = 1

ModelVersion is the version of the document model of the embedded engine.

View Source
const Unlimited = -1

Unlimited disables a limit.

Variables

This section is empty.

Functions

func Build

func Build(ctx context.Context, model *Document, base []byte) ([]byte, error)

Build builds an Office file from a model. Base is the original file: styles, media and everything else not in the model come from it. It may be nil for docx and xlsx (a blank document is used) and is required for pptx.

Example
package main

import (
	"context"
	"fmt"

	coffee "github.com/vitJR1/coffee-templater.go"
)

func main() {
	ctx := context.Background()
	sheet := coffee.SheetFromArrays("Prices", [][]any{
		{"Name", "Price"},
		{"Coffee", 10.5},
		{"Tea", 4},
	})
	doc, err := coffee.Build(ctx, &coffee.Document{Format: coffee.Xlsx, Sheets: []coffee.XlsxSheet{sheet}}, nil)
	if err != nil {
		panic(err)
	}
	text, _ := coffee.ExtractText(ctx, doc)
	fmt.Println(text)
}
Output:
Prices
Name	Price
Coffee	10.5
Tea	4

func ColumnToIndex

func ColumnToIndex(col string) int

ColumnToIndex converts a column name to its 1-based index: "A" → 1, "AA" → 27.

func DateToSerial

func DateToSerial(t time.Time, date1904 bool) float64

DateToSerial converts a time (its wall clock in UTC) to an Excel serial date.

func ExtractText

func ExtractText(ctx context.Context, doc []byte, limits ...Limits) (string, error)

ExtractText returns the plain text of an Office file: paragraphs (docx), tab-separated cells under a sheet name (xlsx), or "--- Slide N ---" blocks with notes (pptx).

func IndexToColumn

func IndexToColumn(n int) string

IndexToColumn converts a 1-based column index to its name: 1 → "A", 27 → "AA".

func ParseRef

func ParseRef(ref string) (col, row int, err error)

ParseRef splits an A1-style reference into 1-based column and row: "$B$3" → 2, 3.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v, for the optional fields of the model: DocxRunStyle{Bold: coffee.Ptr(true)}.

func SerialToDate

func SerialToDate(serial float64, date1904 bool) time.Time

SerialToDate converts an Excel serial date to a time in UTC.

func SheetToArrays

func SheetToArrays(sheet XlsxSheet) [][]any

SheetToArrays returns the values of a sheet as rows of cells, nil for empty cells.

func SheetToObjects

func SheetToObjects(sheet XlsxSheet, headerRow int) []map[string]any

SheetToObjects returns the rows below headerRow (1-based) as maps keyed by the header cells. Empty header cells are named column1, column2…; empty rows are skipped.

Types

type Date

type Date string

Date is a date or date-time in ISO 8601 form, passed to the engine as written. Without a time zone it is naive (as in Excel) and prints as written: Date("2024-05-17"), Date("2024-05-17T10:00:00"). Values of time.Time are absolute instants instead; see Options.TimeZone.

Filters and callbacks receive dates as Date.

func DateOf

func DateOf(t time.Time) Date

DateOf returns the calendar date of t (in t's location) as a naive Date.

func DateTimeOf

func DateTimeOf(t time.Time) Date

DateTimeOf returns the wall-clock time of t (in t's location) as a naive Date.

func (Date) Time

func (d Date) Time() (time.Time, error)

Time parses the date. Naive dates are returned in time.UTC.

type Decimal

type Decimal string

Decimal is an exact decimal number, e.g. Decimal("1234.50"). The number, fixed, round and currency filters round it exactly. Use it for money: coffee.Decimal(d.String()) for shopspring/decimal and similar types.

type Delimiters

type Delimiters struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

Delimiters of tags.

type Document

type Document struct {
	Format       Format `json:"format"`
	ModelVersion int    `json:"modelVersion,omitempty"`

	Parts  []DocxPart  `json:"parts,omitempty"`
	Sheets []XlsxSheet `json:"sheets,omitempty"`
	Slides []PptxSlide `json:"slides,omitempty"`
}

Document is a parsed Office file. Depending on Format, Parts (docx), Sheets (xlsx) or Slides (pptx) is set.

func Parse

func Parse(ctx context.Context, doc []byte, limits ...Limits) (*Document, error)

Parse turns an Office file into a Document. Edit it and pass it to Build with the original file.

func (Document) MarshalJSON

func (d Document) MarshalJSON() ([]byte, error)

type DocxBlock

type DocxBlock struct {
	// Type is "paragraph", "table" or "raw".
	Type string `json:"type"`

	// paragraph
	Style    string       `json:"style,omitempty"` // paragraph style id, e.g. "Heading1"
	Align    string       `json:"align,omitempty"` // left | center | right | justify
	List     *ListRef     `json:"list,omitempty"`  // numbering (bullets, numbered lists)
	Children []DocxInline `json:"children,omitempty"`

	// table
	Rows []DocxTableRow `json:"rows,omitempty"`
	Grid string         `json:"grid,omitempty"` // original <w:tblGrid>

	// Props is the original <w:pPr> (paragraph) or <w:tblPr> (table). Fields above override it.
	Props string `json:"props,omitempty"`
	// XML of a raw block (content controls and anything else not modelled).
	XML string `json:"xml,omitempty"`
}

DocxBlock is a paragraph, a table or raw XML, by Type.

func (DocxBlock) MarshalJSON

func (b DocxBlock) MarshalJSON() ([]byte, error)

type DocxInline

type DocxInline struct {
	// Type is "run", "break", "hyperlink" or "raw".
	Type string `json:"type"`

	// run: Text, where "\n" is a line break and "\t" a tab, and its formatting
	Text string `json:"text,omitempty"`
	DocxRunStyle

	// break: "page" or "column"
	Kind string `json:"kind,omitempty"`

	// hyperlink: an external URL or an internal bookmark, and its content
	URL      string       `json:"url,omitempty"`
	Anchor   string       `json:"anchor,omitempty"`
	Children []DocxInline `json:"children,omitempty"`

	// Props is the original <w:rPr> of a run. Style fields override it.
	Props string `json:"props,omitempty"`
	// XML of raw content (images, fields, bookmarks…).
	XML string `json:"xml,omitempty"`
}

DocxInline is a run, a break, a hyperlink or raw XML, by Type.

func (DocxInline) MarshalJSON

func (in DocxInline) MarshalJSON() ([]byte, error)

type DocxPart

type DocxPart struct {
	// Path in the package, e.g. "word/document.xml", "word/header1.xml".
	Path string `json:"path"`
	// Kind is "body", "header" or "footer".
	Kind   string      `json:"kind"`
	Blocks []DocxBlock `json:"blocks"`
	// SectionProps is the final <w:sectPr> of the body (page size, margins, header references).
	SectionProps string `json:"sectionProps,omitempty"`
}

DocxPart is the body, a header or a footer.

func (DocxPart) MarshalJSON

func (p DocxPart) MarshalJSON() ([]byte, error)

type DocxRunStyle

type DocxRunStyle struct {
	Style     string     `json:"style,omitempty"` // character style id
	Bold      *bool      `json:"bold,omitempty"`
	Italic    *bool      `json:"italic,omitempty"`
	Underline *Underline `json:"underline,omitempty"`
	Strike    *bool      `json:"strike,omitempty"`
	Color     string     `json:"color,omitempty"`     // hex without #, e.g. "FF0000"
	Highlight string     `json:"highlight,omitempty"` // e.g. "yellow"
	Size      *float64   `json:"size,omitempty"`      // points
	Font      string     `json:"font,omitempty"`
	VertAlign string     `json:"vertAlign,omitempty"` // superscript | subscript | baseline
}

DocxRunStyle is the formatting of a run. Nil fields are unset.

type DocxTableCell

type DocxTableCell struct {
	Blocks  []DocxBlock `json:"blocks,omitempty"`
	ColSpan int         `json:"colSpan,omitempty"`
	VMerge  string      `json:"vMerge,omitempty"` // restart | continue
	Props   string      `json:"props,omitempty"`  // original <w:tcPr>
}

DocxTableCell is a table cell.

type DocxTableRow

type DocxTableRow struct {
	Cells []DocxTableCell `json:"cells"`
	Props string          `json:"props,omitempty"` // original <w:trPr>
}

DocxTableRow is a table row.

func (DocxTableRow) MarshalJSON

func (r DocxTableRow) MarshalJSON() ([]byte, error)

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine runs the embedded WebAssembly engine. It is safe for concurrent use: operations take an instance from a pool and return it when done.

Most programs use the default engine implicitly; create one only to change EngineConfig.

func DefaultEngine

func DefaultEngine() (*Engine, error)

DefaultEngine returns the engine used when none is given, creating it on first use.

func NewEngine

func NewEngine(ctx context.Context, cfg EngineConfig) (*Engine, error)

NewEngine compiles the embedded engine. Compilation takes a moment; reuse the Engine.

func (*Engine) Build

func (e *Engine) Build(ctx context.Context, model *Document, base []byte) ([]byte, error)

Build is Build on this engine.

func (*Engine) Close

func (e *Engine) Close(ctx context.Context) error

Close frees the engine. Templates compiled on it can no longer be used.

func (*Engine) DetectFormat

func (e *Engine) DetectFormat(ctx context.Context, doc []byte, limits ...Limits) (Format, error)

DetectFormat is DetectFormat on this engine.

func (*Engine) ExtractText

func (e *Engine) ExtractText(ctx context.Context, doc []byte, limits ...Limits) (string, error)

ExtractText is ExtractText on this engine.

func (*Engine) Info

func (e *Engine) Info(ctx context.Context) (*Info, error)

Info returns the versions and capabilities of the engine.

func (*Engine) Parse

func (e *Engine) Parse(ctx context.Context, doc []byte, limits ...Limits) (*Document, error)

Parse is Parse on this engine.

type EngineConfig

type EngineConfig struct {
	// MaxInstances caps the number of engine instances, i.e. how many operations run in parallel.
	// Each instance is single-threaded and has its own memory. Default: runtime.GOMAXPROCS(0).
	MaxInstances int
	// CacheDir, when set, keeps the machine code compiled from the engine on disk, so later processes
	// start faster. See wazero.NewCompilationCacheWithDir.
	CacheDir string
	// Interpreter runs the engine with the wazero interpreter instead of compiling it to machine code.
	// Slower, but works on platforms without a wazero compiler.
	Interpreter bool
}

EngineConfig configures an Engine.

type Error

type Error struct {
	Problem
	Problems []Problem
}

Error is returned when the engine rejects a template, data, document or model. The embedded Problem is the first one; Problems lists all of them (compilation reports every template mistake at once).

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	coffee "github.com/vitJR1/coffee-templater.go"
)

func main() {
	ctx := context.Background()
	template, _ := os.ReadFile("testdata/conformance/fixtures/broken.docx")

	_, err := coffee.New(coffee.Options{}).Compile(ctx, template)
	var e *coffee.Error
	if errors.As(err, &e) {
		for _, p := range e.Problems {
			fmt.Println(p.Code, p.Tag)
		}
	}
	fmt.Println(errors.Is(err, coffee.ErrUnknownFilter))
}
Output:
unclosed_section {{#items}}
unknown_filter {{company | nope}}
true

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether any of the problems has the code target, so that errors.Is(err, coffee.ErrUnknownFilter) works even when it is not the first problem.

type ErrorCode

type ErrorCode string

ErrorCode identifies a problem reported by the engine. Codes are also errors, so they work with errors.Is:

if errors.Is(err, coffee.ErrUnclosedSection) { … }
const (
	ErrUnclosedTag       ErrorCode = "unclosed_tag"       // missing closing delimiter, or a tag spanning paragraphs/cells
	ErrUnopenedTag       ErrorCode = "unopened_tag"       // closing delimiter without an opening one
	ErrUnclosedSection   ErrorCode = "unclosed_section"   // a section that is never closed
	ErrUnmatchedClose    ErrorCode = "unmatched_close"    // a closing tag without an opening tag, or else outside a section
	ErrInvalidExpression ErrorCode = "invalid_expression" // syntax error inside a tag, or an empty tag
	ErrUnknownFilter     ErrorCode = "unknown_filter"     // a filter that is neither built in nor in Options.Filters
	ErrFilterFailed      ErrorCode = "filter_failed"      // a Go filter returned an error; see Error.Details["hostMessage"]
	ErrMissingValue      ErrorCode = "missing_value"      // strict mode, value missing
	ErrInvalidSection    ErrorCode = "invalid_section"    // sections overlap or cross structure boundaries; misplaced else
	ErrInvalidImage      ErrorCode = "invalid_image"      // the image value is not an image, or the tag is outside a shape (pptx)
	ErrUnsupported       ErrorCode = "unsupported"        // feature not available in this format, malformed XML structure
)

Template mistakes.

const (
	ErrInvalidRequest    ErrorCode = "invalid_request"    // bad frame, invalid fields or tagged values
	ErrInvalidOptions    ErrorCode = "invalid_options"    // invalid Options
	ErrInvalidDocument   ErrorCode = "invalid_document"   // not a zip, broken XML, unsafe zip entries
	ErrUnsupportedFormat ErrorCode = "unsupported_format" // not docx/xlsx/pptx
	ErrInvalidModel      ErrorCode = "invalid_model"      // model does not match the schema
	ErrUnknownTemplate   ErrorCode = "unknown_template"   // template handle not found
	ErrLimitExceeded     ErrorCode = "limit_exceeded"     // a limit was exceeded; Details["limit"] names it
	ErrHostError         ErrorCode = "host_error"         // a callback (NullValue, Stringify) failed
	ErrInternal          ErrorCode = "internal"           // a bug in the engine, or the engine crashed
)

Engine-level problems.

func (ErrorCode) Error

func (c ErrorCode) Error() string

type Filter

type Filter func(value any, args ...any) (any, error)

Filter implements a custom filter. It receives the piped value and the arguments, {{ value | name: arg1, arg2 }}, converted as described for Filter values: objects are map[string]any, arrays []any, numbers float64, dates Date, decimals Decimal, binary data []byte. It may return any value that could appear in template data. An error fails the render with ErrFilterFailed.

type Format

type Format string

Format is an Office file format.

const (
	Docx Format = "docx"
	Xlsx Format = "xlsx"
	Pptx Format = "pptx"
)

func DetectFormat

func DetectFormat(ctx context.Context, doc []byte, limits ...Limits) (Format, error)

DetectFormat detects the format of an Office file.

type Image

type Image struct {
	// Data is the image file: PNG, JPEG, GIF, BMP or SVG are detected; other formats need Extension.
	Data []byte `json:"data"`
	// Extension such as "png", "jpg", "webp", "emf". Detected from Data when empty.
	Extension string `json:"extension,omitempty"`
	// Width and Height in pixels at 96 dpi. A missing one is derived from the aspect ratio; when
	// both are missing, the natural size is used.
	Width  float64 `json:"width,omitempty"`
	Height float64 `json:"height,omitempty"`
	// Alt is the alternative text.
	Alt string `json:"alt,omitempty"`
}

Image is the value of an image tag ({{%logo}}).

type Info

type Info struct {
	CoreVersion  string         `json:"coreVersion"`
	ABIVersion   int            `json:"abiVersion"`
	ModelVersion int            `json:"modelVersion"`
	Formats      []Format       `json:"formats"`
	Features     map[string]any `json:"features"`
}

Info describes the embedded engine.

type InspectResult

type InspectResult struct {
	Format Format `json:"format"`
	// Parts holds the tag tree of each package part.
	Parts []PartTags `json:"parts"`
	// Tags is the tag tree of the whole document, all parts in order.
	Tags []Tag `json:"tags"`
	// Variables lists every data path used, loops marked with []: "client.name", "items[].price".
	Variables []string `json:"variables"`
	// Schema is a sample data object with the shape the template expects: strings for variables,
	// arrays for loops, booleans for conditions and nil for images.
	Schema map[string]any `json:"schema"`
}

InspectResult describes the tags of a template.

type Limits

type Limits struct {
	MaxInputBytes        int64 // input file size; default 100 MiB
	MaxEntries           int64 // zip entries; default 10 000
	MaxUncompressedBytes int64 // total uncompressed size; default 500 MiB
	MaxCompressionRatio  int64 // uncompressed / compressed, per entry larger than 1 MiB; default 200
	MaxXMLDepth          int64 // XML nesting depth; default 256
	MaxOutputBytes       int64 // result size before compression; default 500 MiB
	MaxLoopIterations    int64 // total loop iterations per render; default 1 000 000
	MaxHostCalls         int64 // calls to Filters, NullValue.Func and Stringify per render; default 1 000 000
}

Limits protect against hostile input. Zero keeps the engine default; Unlimited (-1) disables a limit.

type ListRef

type ListRef struct {
	ID    int `json:"id"`
	Level int `json:"level"`
}

ListRef is the numbering of a paragraph.

type Location

type Location struct {
	Paragraph *int   `json:"paragraph,omitempty"`
	Cell      string `json:"cell,omitempty"`
	Slide     *int   `json:"slide,omitempty"`
	Row       *int   `json:"row,omitempty"`
}

Location tells where inside a part an error happened. Fields are filled when known.

type NullMode

type NullMode string

NullMode selects how null and missing values print.

const (
	NullEmpty NullMode = "empty" // print nothing (default)
	NullText  NullMode = "text"  // print NullValue.Text
	NullKeep  NullMode = "keep"  // print the original tag
	NullError NullMode = "error" // fail with ErrMissingValue, like Strict
)

type NullValue

type NullValue struct {
	Mode NullMode
	Text string
	// Func returns the value to print for a tag that resolved to null or a missing value.
	Func func(tag TagInfo) (any, error)
}

NullValue configures null and missing values. Func takes precedence over Mode.

type Options

type Options struct {
	// Delimiters of tags. Default {{ and }}. For example Delimiters{"${", "}"} for ${name}.
	Delimiters Delimiters
	// EscapeChar escapes a delimiter so that it is printed literally: \{{not a tag}}. Default `\`.
	EscapeChar string
	// NoEscape disables escaping.
	NoEscape bool
	// Syntax overrides sigils and keywords of the tag syntax. Empty fields keep the default.
	Syntax Syntax

	// Filters are custom filters: {{ price | money: "EUR" }}. They override built-in filters with the
	// same name.
	Filters map[string]Filter
	// Strict reports missing values as ErrMissingValue instead of printing them as empty.
	Strict bool
	// NullValue decides what a tag resolving to null or a missing value prints. Ignored in Strict mode.
	NullValue NullValue
	// Stringify, when set, converts every non-string value to text (numbers, booleans, dates,
	// arrays, objects). By default numbers print as written, dates as ISO, arrays joined with ", "
	// and objects as JSON.
	Stringify func(value any) (string, error)
	// DateFormat is the default format of dates printed without the date filter, e.g. "DD.MM.YYYY".
	// Default: ISO.
	DateFormat string
	// TimeZone, when set, sends time.Time values as the naive wall-clock time in this location, so
	// {{ d | date: "DD.MM.YYYY" }} shows the local day. By default they are absolute instants
	// printed in UTC. Use Date for values that are naive already.
	TimeZone *time.Location
	// NoLinebreaks keeps "\n" in values as is instead of turning it into a line break
	// (and "\t" into a tab in Word).
	NoLinebreaks bool

	// Limits protect against hostile templates and data.
	Limits Limits
	// Engine runs the templates. Default: DefaultEngine().
	Engine *Engine
}

Options configure a Templater. The zero value gives the defaults.

type PartTags

type PartTags struct {
	Part string `json:"part"`
	Tags []Tag  `json:"tags"`
}

PartTags is the tag tree of one package part.

type PptxInline

type PptxInline struct {
	// Type is "run" or "raw".
	Type string `json:"type"`

	// run: Text, where "\n" is a line break, and its formatting
	Text      string     `json:"text,omitempty"`
	Bold      *bool      `json:"bold,omitempty"`
	Italic    *bool      `json:"italic,omitempty"`
	Underline *Underline `json:"underline,omitempty"`
	Strike    *bool      `json:"strike,omitempty"`
	Size      *float64   `json:"size,omitempty"`  // points
	Color     string     `json:"color,omitempty"` // hex RGB without #
	Font      string     `json:"font,omitempty"`
	Props     string     `json:"props,omitempty"` // original <a:rPr>

	// XML of raw content.
	XML string `json:"xml,omitempty"`
}

PptxInline is a run or raw XML (fields such as the slide number), by Type.

func (PptxInline) MarshalJSON

func (in PptxInline) MarshalJSON() ([]byte, error)

type PptxParagraph

type PptxParagraph struct {
	Align    string       `json:"align,omitempty"` // left | center | right | justify
	Level    *int         `json:"level,omitempty"` // outline level, 0-based
	Children []PptxInline `json:"children,omitempty"`
	Props    string       `json:"props,omitempty"`    // original <a:pPr>
	EndProps string       `json:"endProps,omitempty"` // original <a:endParaRPr>
}

PptxParagraph is a paragraph of a text shape or a table cell.

type PptxShape

type PptxShape struct {
	// Type is "text", "table", "picture", "group", "connector", "graphic" or "other".
	Type string `json:"type"`
	// ID matches shapes on Build (p:cNvPr/@id).
	ID   int64  `json:"id,omitempty"`
	Name string `json:"name,omitempty"`

	// text: Placeholder is the placeholder type, e.g. "title", "body", "subTitle"
	Placeholder string          `json:"placeholder,omitempty"`
	Paragraphs  []PptxParagraph `json:"paragraphs,omitempty"`

	// table
	Rows []PptxTableRow `json:"rows,omitempty"`

	// XML of other shapes; only needed to insert a new shape.
	XML string `json:"xml,omitempty"`
}

PptxShape is a shape of a slide, by Type.

type PptxSlide

type PptxSlide struct {
	// Path in the package, e.g. "ppt/slides/slide1.xml".
	Path string `json:"path"`
	// Shapes in z-order. Shapes missing from the list are removed on Build.
	Shapes []PptxShape `json:"shapes,omitempty"`
	// Notes are the speaker notes as plain text.
	Notes string `json:"notes,omitempty"`
}

PptxSlide is a slide.

type PptxTableCell

type PptxTableCell struct {
	Paragraphs []PptxParagraph `json:"paragraphs,omitempty"`
}

PptxTableCell is a cell of a table shape.

type PptxTableRow

type PptxTableRow struct {
	Cells []PptxTableCell `json:"cells,omitempty"`
}

PptxTableRow is a row of a table shape.

type Problem

type Problem struct {
	Code    ErrorCode `json:"code"`
	Message string    `json:"message"`
	// Part is the package part, e.g. "word/document.xml".
	Part string `json:"part,omitempty"`
	// Tag is the raw tag text, e.g. "{{#items}}".
	Tag      string    `json:"tag,omitempty"`
	Location *Location `json:"location,omitempty"`
	// Details holds extra data, e.g. "hostMessage" for failed filters or "limit".
	Details map[string]any `json:"details,omitempty"`
}

Problem is one problem reported by the engine.

func (Problem) String

func (p Problem) String() string

type SectionMode

type SectionMode string

SectionMode is the kind of a section tag.

const (
	ModeSection  SectionMode = "section"  // {{#x}}: loop, context or truthy check
	ModeInverted SectionMode = "inverted" // {{^x}}
	ModeIf       SectionMode = "if"       // {{#if x}}
	ModeUnless   SectionMode = "unless"   // {{#unless x}}
	ModeEach     SectionMode = "each"     // {{#each x}}
)

type Syntax

type Syntax struct {
	Section  string `json:"section,omitempty"`  // "#": {{#items}}
	Inverted string `json:"inverted,omitempty"` // "^": {{^items}}
	Close    string `json:"close,omitempty"`    // "/": {{/items}}
	Image    string `json:"image,omitempty"`    // "%": {{%logo}}
	Else     string `json:"else,omitempty"`     // "else": {{else}}
	If       string `json:"if,omitempty"`       // "if": {{#if paid}}
	Unless   string `json:"unless,omitempty"`   // "unless": {{#unless paid}}
	Each     string `json:"each,omitempty"`     // "each": {{#each items}}
}

Syntax holds the sigils and keywords of tags. Empty fields keep the default.

type Tag

type Tag struct {
	Type       TagType `json:"type"`
	Path       string  `json:"path"`
	Expression string  `json:"expression"`
	Raw        string  `json:"raw"`
	// Filters of a variable tag.
	Filters []string `json:"filters,omitempty"`
	// Mode, Children and ElseChildren belong to section tags.
	Mode         SectionMode `json:"mode,omitempty"`
	Children     []Tag       `json:"children,omitempty"`
	ElseChildren []Tag       `json:"elseChildren,omitempty"`
}

Tag is a node of the tag tree.

type TagInfo

type TagInfo struct {
	// Raw is the full tag text with delimiters, e.g. "{{client.name}}".
	Raw string `json:"raw"`
	// Expression is the text inside the tag, e.g. "client.name | upper".
	Expression string `json:"expression"`
	// Part is the package part of the tag, e.g. "word/document.xml".
	Part string `json:"part"`
}

TagInfo describes a tag, for NullValue.Func.

type TagType

type TagType string

TagType is the kind of a tag.

const (
	TagVariable TagType = "variable"
	TagImage    TagType = "image"
	TagSection  TagType = "section"
)

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template is a compiled template. It is safe for concurrent use: each engine instance compiles the template on first use and keeps it until Close.

func (*Template) Close

func (tpl *Template) Close() error

Close frees the template in the engine. Calling it again does nothing.

func (*Template) Format

func (tpl *Template) Format() Format

Format of the template.

func (*Template) Inspect

func (tpl *Template) Inspect(ctx context.Context) (*InspectResult, error)

Inspect describes the tags of the template: the tag tree, the variable paths and a sample data shape.

Example
package main

import (
	"context"
	"fmt"
	"os"

	coffee "github.com/vitJR1/coffee-templater.go"
)

func main() {
	ctx := context.Background()
	template, _ := os.ReadFile("testdata/conformance/fixtures/invoice.docx")

	res, err := coffee.New(coffee.Options{}).Inspect(ctx, template)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Variables[:3])
}
Output:
[number client.name items[].name]

func (*Template) Parts

func (tpl *Template) Parts() []string

Parts are the package parts that contain template text, e.g. "word/document.xml".

func (*Template) Render

func (tpl *Template) Render(ctx context.Context, data any) ([]byte, error)

Render renders the template with data and returns the document.

Data is converted like encoding/json does (struct tags included), plus: time.Time → date, Date → naive date, Decimal and *big.Float → exact decimal, []byte → binary data (images), Image for image tags. Cancelling ctx interrupts the engine.

type Templater

type Templater struct {
	// contains filtered or unexported fields
}

Templater renders templates with one configuration. Create it once and reuse it; it is safe for concurrent use.

func New

func New(opts Options) *Templater

New returns a Templater with the given options.

func (*Templater) Compile

func (t *Templater) Compile(ctx context.Context, template []byte) (*Template, error)

Compile parses a template once, so that it can be rendered many times. It reports every template mistake at once (see Error.Problems). Close the template when done.

Example
package main

import (
	"context"
	"fmt"
	"os"

	coffee "github.com/vitJR1/coffee-templater.go"
)

func main() {
	ctx := context.Background()
	template, _ := os.ReadFile("testdata/conformance/fixtures/report.xlsx")

	tpl, err := coffee.New(coffee.Options{}).Compile(ctx, template)
	if err != nil {
		panic(err)
	}
	defer tpl.Close()

	for _, title := range []string{"Q1", "Q2"} {
		doc, err := tpl.Render(ctx, map[string]any{"title": title, "items": []any{}})
		if err != nil {
			panic(err)
		}
		model, _ := coffee.Parse(ctx, doc)
		fmt.Println(model.Sheets[0].Rows[0].Cells[0].Value)
	}
}
Output:
Report: Q1
Report: Q2

func (*Templater) Inspect

func (t *Templater) Inspect(ctx context.Context, template []byte) (*InspectResult, error)

Inspect describes the tags of a template.

func (*Templater) Render

func (t *Templater) Render(ctx context.Context, template []byte, data any) ([]byte, error)

Render compiles template, renders it with data and returns the document. To render a template many times, Compile it once instead.

type Underline

type Underline struct {
	On   bool
	Type string // when set, the underline type; On is implied
}

Underline is on/off, or an underline type such as "double" or "wave".

func (Underline) MarshalJSON

func (u Underline) MarshalJSON() ([]byte, error)

func (*Underline) UnmarshalJSON

func (u *Underline) UnmarshalJSON(b []byte) error

type XlsxCell

type XlsxCell struct {
	// Ref is the A1-style reference. When empty, the cell goes to the column after the previous one.
	Ref string `json:"ref,omitempty"`
	// Value is a string, float64, bool or nil. Date cells hold an ISO string with Type "date".
	Value any `json:"value,omitempty"`
	// Type is "date" for date-formatted numbers, "error" for #N/A and the like.
	Type string `json:"type,omitempty"`
	// Formula without the leading =. Value holds the cached result.
	Formula string `json:"formula,omitempty"`
	// Style is an index into the workbook cell formats (cellXfs).
	Style *int `json:"style,omitempty"`
	// RichText is the original rich-text XML (<r> runs), used while Value equals its plain text.
	RichText string `json:"richText,omitempty"`
}

XlsxCell is a cell.

type XlsxRow

type XlsxRow struct {
	// Index is the 1-based row number.
	Index  int        `json:"index"`
	Height *float64   `json:"height,omitempty"` // points
	Hidden *bool      `json:"hidden,omitempty"`
	Cells  []XlsxCell `json:"cells,omitempty"`
}

XlsxRow is a sheet row.

type XlsxSheet

type XlsxSheet struct {
	Name string `json:"name"`
	// Path of an existing sheet. Leave it empty to create a new sheet on Build.
	Path string    `json:"path,omitempty"`
	Rows []XlsxRow `json:"rows,omitempty"`
	// Merges are merged ranges, e.g. "A1:C1".
	Merges []string `json:"merges,omitempty"`
}

XlsxSheet is a worksheet.

func SheetFromArrays

func SheetFromArrays(name string, rows [][]any) XlsxSheet

SheetFromArrays builds a new sheet from rows of values: strings, numbers, booleans, time.Time (written as date cells) and nil for empty cells.

Directories

Path Synopsis
internal
wasm
Package wasm embeds the coffee-templater-engine WebAssembly binary.
Package wasm embeds the coffee-templater-engine WebAssembly binary.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL