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 ¶
- Constants
- func Build(ctx context.Context, model *Document, base []byte) ([]byte, error)
- func ColumnToIndex(col string) int
- func DateToSerial(t time.Time, date1904 bool) float64
- func ExtractText(ctx context.Context, doc []byte, limits ...Limits) (string, error)
- func IndexToColumn(n int) string
- func ParseRef(ref string) (col, row int, err error)
- func Ptr[T any](v T) *T
- func SerialToDate(serial float64, date1904 bool) time.Time
- func SheetToArrays(sheet XlsxSheet) [][]any
- func SheetToObjects(sheet XlsxSheet, headerRow int) []map[string]any
- type Date
- type Decimal
- type Delimiters
- type Document
- type DocxBlock
- type DocxInline
- type DocxPart
- type DocxRunStyle
- type DocxTableCell
- type DocxTableRow
- type Engine
- func (e *Engine) Build(ctx context.Context, model *Document, base []byte) ([]byte, error)
- func (e *Engine) Close(ctx context.Context) error
- func (e *Engine) DetectFormat(ctx context.Context, doc []byte, limits ...Limits) (Format, error)
- func (e *Engine) ExtractText(ctx context.Context, doc []byte, limits ...Limits) (string, error)
- func (e *Engine) Info(ctx context.Context) (*Info, error)
- func (e *Engine) Parse(ctx context.Context, doc []byte, limits ...Limits) (*Document, error)
- type EngineConfig
- type Error
- type ErrorCode
- type Filter
- type Format
- type Image
- type Info
- type InspectResult
- type Limits
- type ListRef
- type Location
- type NullMode
- type NullValue
- type Options
- type PartTags
- type PptxInline
- type PptxParagraph
- type PptxShape
- type PptxSlide
- type PptxTableCell
- type PptxTableRow
- type Problem
- type SectionMode
- type Syntax
- type Tag
- type TagInfo
- type TagType
- type Template
- type Templater
- type Underline
- type XlsxCell
- type XlsxRow
- type XlsxSheet
Examples ¶
Constants ¶
const EngineSHA256 = wasm.SHA256
EngineSHA256 is the sha256 of the embedded coffee_core.wasm.
const EngineVersion = wasm.Version
EngineVersion is the version of the embedded coffee-templater-engine.
const ModelVersion = 1
ModelVersion is the version of the document model of the embedded engine.
const Unlimited = -1
Unlimited disables a limit.
Variables ¶
This section is empty.
Functions ¶
func Build ¶
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 ¶
ColumnToIndex converts a column name to its 1-based index: "A" → 1, "AA" → 27.
func DateToSerial ¶
DateToSerial converts a time (its wall clock in UTC) to an Excel serial date.
func ExtractText ¶
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 ¶
IndexToColumn converts a 1-based column index to its name: 1 → "A", 27 → "AA".
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 ¶
SerialToDate converts an Excel serial date to a time in UTC.
func SheetToArrays ¶
SheetToArrays returns the values of a sheet as rows of cells, nil for empty cells.
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 DateTimeOf ¶
DateTimeOf returns the wall-clock time of t (in t's location) as a naive Date.
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 ¶
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 ¶
Parse turns an Office file into a Document. Edit it and pass it to Build with the original file.
func (Document) MarshalJSON ¶
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 ¶
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 ¶
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 ¶
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) DetectFormat ¶
DetectFormat is DetectFormat on this engine.
func (*Engine) ExtractText ¶
ExtractText is ExtractText 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 ¶
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
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.
type Filter ¶
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 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 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 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 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.
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 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) 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 ¶
Parts are the package parts that contain template text, e.g. "word/document.xml".
func (*Template) Render ¶
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 (*Templater) Compile ¶
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
type Underline ¶
Underline is on/off, or an underline type such as "double" or "wave".
func (Underline) MarshalJSON ¶
func (*Underline) UnmarshalJSON ¶
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 ¶
SheetFromArrays builds a new sheet from rows of values: strings, numbers, booleans, time.Time (written as date cells) and nil for empty cells.