stencil

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: EPL-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package stencil provides a powerful template engine for Microsoft Word documents (DOCX). It enables dynamic document generation by processing templates with placeholders, control structures, and built-in functions.

Basic Usage:

// Prepare a template from a file
tmpl, err := stencil.PrepareFile("template.docx")
if err != nil {
    log.Fatal(err)
}
defer tmpl.Close()

// Render with data
data := stencil.TemplateData{
    "name": "John Doe",
    "items": []map[string]interface{}{
        {"product": "Widget", "price": 19.99},
        {"product": "Gadget", "price": 29.99},
    },
}

output, err := tmpl.Render(data)
if err != nil {
    log.Fatal(err)
}

// Save the result
result, err := os.Create("output.docx")
if err != nil {
    log.Fatal(err)
}
defer result.Close()

_, err = io.Copy(result, output)
if err != nil {
    log.Fatal(err)
}

Template Syntax:

Variables: {{name}}, {{customer.address}}, {{price * 1.2}}

Conditionals: {{if condition}}...{{else}}...{{end}}

Loops: {{for item in items}}...{{end}}

Functions: {{uppercase(name)}}, {{format("%.2f", price)}}

For more information on template syntax and available functions, see the README.

Package stencil provides a powerful template engine for Microsoft Word documents (DOCX).

Go-stencil enables dynamic document generation by processing templates with placeholders, control structures, and built-in functions. It's designed for generating reports, invoices, contracts, and other documents that require programmatic content injection.

Quick Start

The simplest way to use go-stencil is through the package-level functions:

tmpl, err := stencil.PrepareFile("template.docx")
if err != nil {
    log.Fatal(err)
}
defer tmpl.Close()

data := stencil.TemplateData{
    "name": "John Doe",
    "date": time.Now(),
}

output, err := tmpl.Render(data)
if err != nil {
    log.Fatal(err)
}

// Save to file
os.WriteFile("output.docx", output.Bytes(), 0644)

Template Syntax

All template expressions use double curly braces {{}}:

Variables and Expressions:

{{name}}                    - Simple variable
{{customer.address}}        - Nested field access
{{price * 1.2}}            - Mathematical expression
{{(basePrice + tax) * qty}} - Complex expression

Control Structures:

{{if condition}}...{{end}}           - Conditional
{{if x > 5}}...{{else}}...{{end}}   - If-else
{{if x}}...{{elsif y}}...{{end}}    - If-elsif chain
{{unless condition}}...{{end}}       - Negated conditional
{{for item in items}}...{{end}}      - Loop
{{for i, item in items}}...{{end}}   - Indexed loop

Functions:

{{uppercase(name)}}                  - String transformation
{{format("%.2f", price)}}           - Number formatting
{{date("2006-01-02", timestamp)}}   - Date formatting
{{sum(numbers)}}                     - Aggregate function

Document Operations:

{{pageBreak()}}                      - Insert page break
{{html("<b>Bold text</b>")}}        - Insert HTML
{{include "Fragment Name"}}          - Include fragment

Architecture

The package is organized into several sub-packages:

  • xml: XML structure definitions for DOCX files (Document, Paragraph, Run, Table, etc.)
  • render: Pure helper functions for template rendering (control structure detection, run merging)

The main package provides:

  • Template preparation and rendering (PrepareFile, Render)
  • Data context management (TemplateData)
  • Function registry (built-in and custom functions)
  • Configuration and caching
  • Error handling

Advanced Usage

Custom Functions:

engine := stencil.New()
engine.RegisterFunction("greet", func(name string) string {
    return "Hello, " + name + "!"
})

Configuration:

config := &stencil.Config{
    CacheMaxSize:    100,
    CacheExpiration: 24 * time.Hour,
}
engine := stencil.NewWithConfig(config)

Fragment Handling:

fragments := map[string]io.Reader{
    "Header": headerFile,
    "Footer": footerFile,
}
output, err := tmpl.RenderWithFragments(data, fragments)

Performance

Templates are compiled during preparation and can be reused multiple times with different data. Enable caching to avoid re-parsing templates:

stencil.SetGlobalConfig(&stencil.Config{
    CacheMaxSize:    100,
    CacheExpiration: 1 * time.Hour,
})

Benchmarks show rendering performance of 10,000+ documents per second for typical templates.

Error Handling

The package defines several error types for specific failure cases:

  • TemplateError: Template syntax errors
  • RenderError: Errors during rendering
  • ParseError: Expression parsing errors

Check error types using errors.As():

if errors.As(err, &stencil.TemplateError{}) {
    // Handle template syntax error
}

Thread Safety

PreparedTemplate is safe for concurrent use. Multiple goroutines can call Render() on the same template simultaneously. The Engine and its cache are also thread-safe.

DOCX File Structure

DOCX files are ZIP archives containing XML files. The main document content is in word/document.xml. Go-stencil parses this XML, processes templates, and generates a new DOCX file with the rendered content.

Key XML structures:

  • Document: Top-level container
  • Body: Document body containing elements
  • Paragraph: Text paragraph with formatting
  • Run: Sequence of text with consistent formatting
  • Table: Table with rows and cells

Limitations

Some DOCX features are not yet fully supported:

  • Complex table merging (partial support)
  • Custom XML parts
  • Embedded objects (charts, diagrams)
  • Track changes and comments

See Also

For more examples and detailed documentation:

  • README.md: Comprehensive guide and feature list
  • examples/: Example templates and usage patterns
  • CLAUDE.md: Development philosophy and roadmap

Package stencil provides custom error types for better error handling and reporting.

Index

Constants

View Source
const (
	// ID ranges for relationship management
	MainTemplateIDRange  = 999  // Main template uses rId1 - rId999
	FragmentIDRangeSize  = 100  // Each fragment gets 100 IDs
	FragmentIDRangeStart = 1000 // Fragments start at rId1000

)

Variables

View Source
var DefaultEngine = New()

DefaultEngine is the global default engine instance. It uses the global configuration and function registry.

View Source
var (
	ParseDocument = xml.ParseDocument
)

Re-export functions

Functions

func CallFunction

func CallFunction(name string, data TemplateData, args ...interface{}) (interface{}, error)

CallFunction is a helper to call a function by name with arguments

func ClearCache

func ClearCache()

ClearCache clears the global template cache.

func Debug

func Debug(format string, args ...interface{})

func Error

func Error(format string, args ...interface{})

func EvaluateBinaryOperation

func EvaluateBinaryOperation(left interface{}, operator string, right interface{}) (interface{}, error)

EvaluateBinaryOperation evaluates a binary operation between two values

func EvaluateVariable

func EvaluateVariable(expression string, data TemplateData) (interface{}, error)

EvaluateVariable evaluates a variable expression with support for nested field access

func FindTemplateTokens

func FindTemplateTokens(input string) []string

FindTemplateTokens finds all template tokens in a string This is a utility function for debugging and analysis

func FormatValue

func FormatValue(value interface{}) string

FormatValue converts a value to its string representation

func Info

func Info(format string, args ...interface{})

func NewDocumentError

func NewDocumentError(operation, path string, cause error) error

NewDocumentError creates a new document error

func NewEvaluationError

func NewEvaluationError(expression string, cause error) error

NewEvaluationError creates a new evaluation error

func NewFunctionError

func NewFunctionError(function string, args []interface{}, message string) error

NewFunctionError creates a new function error

func NewParseError

func NewParseError(message, token string, position int) error

NewParseError creates a new parse error

func NewTemplateError

func NewTemplateError(message string, line, column int) error

NewTemplateError creates a new template error with position information

func ProcessTableColumnMarkers

func ProcessTableColumnMarkers(doc *Document) error

ProcessTableColumnMarkers processes column markers in the document

func ProcessTableRowMarkers

func ProcessTableRowMarkers(doc *Document) error

ProcessTableRowMarkers processes table row markers in a document and removes marked rows

func ProcessTemplateWithFragments

func ProcessTemplateWithFragments(content string, data TemplateData, fragments map[string]*fragment) (string, error)

ProcessTemplateWithFragments processes a template string with control structures and fragments

func RegisterFunctionsFromProvider

func RegisterFunctionsFromProvider(provider FunctionProvider) error

RegisterFunctionsFromProvider registers functions from a provider in the global registry.

func RegisterGlobalFunction

func RegisterGlobalFunction(name string, fn Function) error

RegisterGlobalFunction adds a custom function to the global function registry.

func SetCacheConfig

func SetCacheConfig(maxSize int, ttl time.Duration)

SetCacheConfig updates the global cache configuration.

func SetGlobalConfig

func SetGlobalConfig(config *Config)

SetGlobalConfig sets the global configuration

func SetLogger

func SetLogger(logger *Logger)

Global logging functions

func UpdateLoggerFromConfig

func UpdateLoggerFromConfig()

UpdateLoggerFromConfig updates the global logger based on the current global configuration

func Warn

func Warn(format string, args ...interface{})

func WithContext

func WithContext(err error, operation string, context map[string]interface{}) error

WithContext wraps an error with additional context

Types

type Alignment

type Alignment = xml.Alignment

Re-export paragraph types

type BinaryOpNode

type BinaryOpNode struct {
	Left     ExpressionNode
	Operator string
	Right    ExpressionNode
}

BinaryOpNode represents a binary operation

func (*BinaryOpNode) Evaluate

func (n *BinaryOpNode) Evaluate(data TemplateData) (interface{}, error)

func (*BinaryOpNode) String

func (n *BinaryOpNode) String() string

type Body

type Body = xml.Body

Re-export document types

func RenderBody

func RenderBody(body *Body, data TemplateData) (*Body, error)

RenderBody renders a document body

func RenderBodyWithContext

func RenderBodyWithContext(body *Body, data TemplateData, ctx *renderContext) (*Body, error)

RenderBodyWithContext renders a document body with context

func RenderBodyWithControlStructures

func RenderBodyWithControlStructures(body *Body, data TemplateData, ctx *renderContext) (*Body, error)

RenderBodyWithControlStructures renders a document body handling control structures

type BodyElement

type BodyElement = xml.BodyElement

Re-export core types and interfaces

func MergeConsecutiveTables

func MergeConsecutiveTables(elements []BodyElement) []BodyElement

MergeConsecutiveTables merges consecutive tables that were split by template loops This implementation is content-agnostic and merges based purely on position and structure

type BorderProperties

type BorderProperties = xml.BorderProperties

Re-export table types

type Break

type Break = xml.Break

Re-export run types

type CacheConfig

type CacheConfig struct {
	// MaxSize is the maximum number of templates to cache. 0 disables caching.
	MaxSize int
	// TTL is the time-to-live for cached templates. 0 means no expiration.
	TTL time.Duration
}

CacheConfig contains configuration options for the template cache

type CellMargin

type CellMargin = xml.CellMargin

Re-export table types

type Color

type Color = xml.Color

Re-export run types

type Config

type Config struct {
	// CacheMaxSize is the maximum number of templates to cache. 0 disables caching.
	CacheMaxSize int
	// CacheTTL is the time-to-live for cached templates. 0 means no expiration.
	CacheTTL time.Duration
	// LogLevel controls the verbosity of logging (debug, info, warn, error)
	LogLevel string
	// MaxRenderDepth controls the maximum depth of nested template includes/fragments
	MaxRenderDepth int
	// StrictMode enables strict template validation and error handling
	StrictMode bool
}

Config contains all configuration options for the Stencil engine

func ConfigFromEnvironment

func ConfigFromEnvironment() *Config

ConfigFromEnvironment creates a configuration from environment variables

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration

func GetGlobalConfig

func GetGlobalConfig() *Config

GetGlobalConfig returns the global configuration

func NewConfigWithDefaults

func NewConfigWithDefaults(overrides *Config) *Config

NewConfigWithDefaults creates a new configuration with defaults applied to unset fields

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid

type ContentTypeDefault

type ContentTypeDefault struct {
	Extension   string `xml:"Extension,attr"`
	ContentType string `xml:"ContentType,attr"`
}

ContentTypeDefault represents a default content type mapping by extension

type ContentTypeOverride

type ContentTypeOverride struct {
	PartName    string `xml:"PartName,attr"`
	ContentType string `xml:"ContentType,attr"`
}

ContentTypeOverride represents a content type override for a specific part

type ContentTypes

type ContentTypes struct {
	XMLName   xml.Name              `xml:"Types"`
	Namespace string                `xml:"xmlns,attr"`
	Defaults  []ContentTypeDefault  `xml:"Default"`
	Overrides []ContentTypeOverride `xml:"Override"`
}

ContentTypes represents the [Content_Types].xml file

type ContextError

type ContextError struct {
	Operation string
	Context   map[string]interface{}
	Cause     error
}

ContextError adds context to an existing error

func (*ContextError) Error

func (e *ContextError) Error() string

func (*ContextError) Unwrap

func (e *ContextError) Unwrap() error

type ControlParser

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

ControlParser parses control structures from template tokens

type ControlStructure

type ControlStructure interface {
	Render(data TemplateData) (string, error)
	RenderWithContext(data TemplateData, ctx *renderContext) (string, error)
	String() string
}

ControlStructure represents a control flow structure in templates

func ParseControlStructures

func ParseControlStructures(content string) ([]ControlStructure, error)

ParseControlStructures parses tokens into control structures

type DefaultFunctionRegistry

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

DefaultFunctionRegistry is the default implementation of FunctionRegistry

func NewFunctionRegistry

func NewFunctionRegistry() *DefaultFunctionRegistry

NewFunctionRegistry creates a new function registry

func (*DefaultFunctionRegistry) GetFunction

func (r *DefaultFunctionRegistry) GetFunction(name string) (Function, bool)

func (*DefaultFunctionRegistry) ListFunctions

func (r *DefaultFunctionRegistry) ListFunctions() []string

func (*DefaultFunctionRegistry) RegisterFunction

func (r *DefaultFunctionRegistry) RegisterFunction(fn Function) error

type Document

type Document = xml.Document

Re-export document types

func RenderDocument

func RenderDocument(doc *Document, data TemplateData) (*Document, error)

RenderDocument renders a document with the given data

func RenderDocumentWithContext

func RenderDocumentWithContext(doc *Document, data TemplateData, ctx *renderContext) (*Document, error)

RenderDocumentWithContext renders a document with the given data and context

type DocumentError

type DocumentError struct {
	Operation string
	Path      string
	Cause     error
}

DocumentError represents an error during document operations

func (*DocumentError) Error

func (e *DocumentError) Error() string

func (*DocumentError) Unwrap

func (e *DocumentError) Unwrap() error

type DocumentPart

type DocumentPart struct {
	Name    string
	Content []byte
}

DocumentPart represents a part of the DOCX package

type DocumentStyle

type DocumentStyle struct {
	XMLName xml.Name `xml:"style"`
	Type    string   `xml:"type,attr"`
	StyleID string   `xml:"styleId,attr"`
	RawXML  []byte   `xml:",innerxml"` // Store the entire style definition as raw XML
}

DocumentStyle represents a single w:style element (renamed to avoid conflict with table style)

type DocxReader

type DocxReader struct {
	Parts map[string]*zip.File
	// contains filtered or unexported fields
}

DocxReader handles reading and parsing DOCX files

func DocxReaderFromFile

func DocxReaderFromFile(path string) (*DocxReader, error)

DocxReaderFromFile creates a DocxReader from a file path

func NewDocxReader

func NewDocxReader(r io.ReaderAt, size int64) (*DocxReader, error)

NewDocxReader creates a new DOCX reader

func (*DocxReader) GetDocumentXML

func (dr *DocxReader) GetDocumentXML() (string, error)

GetDocumentXML retrieves the content of word/document.xml

func (*DocxReader) GetPart

func (dr *DocxReader) GetPart(partName string) ([]byte, error)

GetPart retrieves the content of a specific part

func (*DocxReader) GetRelationships

func (dr *DocxReader) GetRelationships(partName string) ([]Relationship, error)

GetRelationships retrieves relationships for a given part

func (*DocxReader) GetRelationshipsXML

func (dr *DocxReader) GetRelationshipsXML() (string, error)

GetRelationshipsXML retrieves the content of word/_rels/document.xml.rels

func (*DocxReader) ListParts

func (dr *DocxReader) ListParts() []string

ListParts returns a list of all part names in the DOCX

type ElementWithPath

type ElementWithPath struct {
	Type    string   // "text" or "break"
	Content string   // text content (for text elements)
	Path    []string // formatting path
}

ElementWithPath represents an element with its formatting path

type ElsIfNode

type ElsIfNode struct {
	Condition ExpressionNode
	Body      []ControlStructure
}

ElsIfNode represents an elsif/elseif clause

func (*ElsIfNode) String

func (n *ElsIfNode) String() string

type Empty

type Empty = xml.Empty

Re-export core types and interfaces

type Engine

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

Engine provides the main API for working with templates. Use New() to create a new engine instance.

func New

func New() *Engine

New creates a new template engine with default configuration.

func NewWithConfig

func NewWithConfig(config *Config) *Engine

NewWithConfig creates a new template engine with custom configuration.

func NewWithOptions

func NewWithOptions(opts ...Option) *Engine

NewWithOptions creates a new engine with the specified options.

func (*Engine) ClearCache

func (e *Engine) ClearCache()

ClearCache removes all templates from the cache.

func (*Engine) Close

func (e *Engine) Close() error

Close releases any resources held by the engine.

func (*Engine) Config

func (e *Engine) Config() *Config

Config returns the engine's configuration.

func (*Engine) Prepare

func (e *Engine) Prepare(r io.Reader) (*PreparedTemplate, error)

Prepare loads and compiles a template from an io.Reader.

func (*Engine) PrepareFile

func (e *Engine) PrepareFile(path string) (*PreparedTemplate, error)

PrepareFile loads and compiles a template from a file path. The template is cached if caching is enabled in the configuration.

func (*Engine) RegisterFunction

func (e *Engine) RegisterFunction(name string, fn Function) error

RegisterFunction adds a custom function that can be used in templates. The function name must be a valid identifier and not conflict with built-in functions.

func (*Engine) RegisterFunctionsFromProvider

func (e *Engine) RegisterFunctionsFromProvider(provider FunctionProvider) error

RegisterFunctionsFromProvider registers all functions from a provider. This is useful for adding a suite of related functions at once.

func (*Engine) SetConfig

func (e *Engine) SetConfig(config *Config)

SetConfig updates the engine's configuration. Note that some settings (like cache size) may not take effect immediately.

type EvaluationError

type EvaluationError struct {
	Expression string
	Cause      error
}

EvaluationError represents an error during expression evaluation

func (*EvaluationError) Error

func (e *EvaluationError) Error() string

func (*EvaluationError) Unwrap

func (e *EvaluationError) Unwrap() error

type ExpressionContentNode

type ExpressionContentNode struct {
	Expression ExpressionNode
}

ExpressionContentNode represents an expression that should be evaluated and output

func (*ExpressionContentNode) Render

func (n *ExpressionContentNode) Render(data TemplateData) (string, error)

func (*ExpressionContentNode) RenderWithContext

func (n *ExpressionContentNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)

func (*ExpressionContentNode) String

func (n *ExpressionContentNode) String() string

type ExpressionNode

type ExpressionNode interface {
	String() string
	Evaluate(data TemplateData) (interface{}, error)
}

ExpressionNode represents a node in the expression AST

func ParseExpression

func ParseExpression(expr string) (ExpressionNode, error)

ParseExpression parses an expression string into an AST

func ParseExpressionStrict

func ParseExpressionStrict(expr string) (ExpressionNode, error)

ParseExpressionStrict parses an expression string into an AST and requires full token consumption. This is used by validation flows to reject trailing tokens such as "name name2".

type ExpressionParser

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

ExpressionParser parses expressions into AST nodes

type ExpressionToken

type ExpressionToken struct {
	Type  ExpressionTokenType
	Value string
	Pos   int
}

ExpressionToken represents a token in an expression

func TokenizeExpression

func TokenizeExpression(expr string) ([]ExpressionToken, error)

TokenizeExpression tokenizes an expression string

type ExpressionTokenType

type ExpressionTokenType int
const (
	ExprTokenIdentifier ExpressionTokenType = iota
	ExprTokenNumber
	ExprTokenString
	ExprTokenOperator
	ExprTokenLeftParen
	ExprTokenRightParen
	ExprTokenComma
	ExprTokenEOF
	ExprTokenInvalid
)

type ExtractReferencesInput

type ExtractReferencesInput struct {
	DocxBytes          []byte `json:"-"`
	TemplateRevisionID string `json:"templateRevisionId,omitempty"`
}

ExtractReferencesInput controls reference extraction behavior.

type ExtractReferencesResult

type ExtractReferencesResult struct {
	References []TemplateTokenRef `json:"references"`
	Metadata   StencilMetadata    `json:"metadata"`
}

ExtractReferencesResult contains parsed references extracted from template tokens.

func ExtractReferences

func ExtractReferences(input ExtractReferencesInput) (ExtractReferencesResult, error)

ExtractReferences extracts variable/function/control references from parsed token ASTs.

type FieldAccessNode

type FieldAccessNode struct {
	Object ExpressionNode
	Field  string
}

FieldAccessNode represents field access (obj.field)

func (*FieldAccessNode) Evaluate

func (n *FieldAccessNode) Evaluate(data TemplateData) (interface{}, error)

func (*FieldAccessNode) String

func (n *FieldAccessNode) String() string

type FieldDefinition

type FieldDefinition struct {
	Path       string `json:"path"`
	Type       string `json:"type"`
	Nullable   bool   `json:"nullable,omitempty"`
	Collection bool   `json:"collection,omitempty"`
}

FieldDefinition defines one field path and type.

type Fields

type Fields map[string]interface{}

type Font

type Font = xml.Font

Re-export run types

type ForNode

type ForNode struct {
	Variable   string
	IndexVar   string // Optional index variable for indexed loops
	Collection ExpressionNode
	Body       []ControlStructure
}

ForNode represents a for loop

func (*ForNode) Render

func (n *ForNode) Render(data TemplateData) (string, error)

func (*ForNode) RenderWithContext

func (n *ForNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)

func (*ForNode) String

func (n *ForNode) String() string

type Function

type Function interface {
	// Call executes the function with the given arguments
	Call(args ...interface{}) (interface{}, error)

	// Name returns the function name
	Name() string

	// MinArgs returns the minimum number of arguments required
	MinArgs() int

	// MaxArgs returns the maximum number of arguments allowed (-1 for unlimited)
	MaxArgs() int
}

Function represents a callable function in templates

func NewSimpleFunction

func NewSimpleFunction(name string, minArgs, maxArgs int, handler func(args ...interface{}) (interface{}, error)) Function

type FunctionCallNode

type FunctionCallNode struct {
	Name string
	Args []ExpressionNode
}

FunctionCallNode represents a function call

func (*FunctionCallNode) Evaluate

func (n *FunctionCallNode) Evaluate(data TemplateData) (interface{}, error)

func (*FunctionCallNode) String

func (n *FunctionCallNode) String() string

type FunctionDefinition

type FunctionDefinition struct {
	Name       string     `json:"name"`
	MinArgs    int        `json:"minArgs,omitempty"`
	MaxArgs    int        `json:"maxArgs,omitempty"`
	ArgKinds   [][]string `json:"argKinds,omitempty"`
	ReturnKind string     `json:"returnKind,omitempty"`
}

FunctionDefinition defines one function signature.

type FunctionError

type FunctionError struct {
	Function string
	Args     []interface{}
	Message  string
}

FunctionError represents an error in a template function call

func (*FunctionError) Error

func (e *FunctionError) Error() string

type FunctionProvider

type FunctionProvider interface {
	// ProvideFunctions returns a map of function name to Function implementation
	ProvideFunctions() map[string]Function
}

FunctionProvider interface allows for providing custom functions during template rendering

type FunctionRegistry

type FunctionRegistry interface {
	// RegisterFunction adds a function to the registry
	RegisterFunction(fn Function) error

	// GetFunction retrieves a function by name
	GetFunction(name string) (Function, bool)

	// ListFunctions returns all registered function names
	ListFunctions() []string
}

FunctionRegistry manages available functions

func CreateRegistryWithProvider

func CreateRegistryWithProvider(provider FunctionProvider) (FunctionRegistry, error)

CreateRegistryWithProvider creates a new registry and registers functions from a provider

func GetDefaultFunctionRegistry

func GetDefaultFunctionRegistry() FunctionRegistry

GetDefaultFunctionRegistry returns the default global function registry

type GridColumn

type GridColumn = xml.GridColumn

Re-export table types

type GridSpan

type GridSpan = xml.GridSpan

Re-export table types

type HTMLNode

type HTMLNode struct {
	Type     string
	Content  string
	Children []*HTMLNode
	Attrs    map[string]string
}

HTMLNode represents a node in the HTML parse tree

type HTMLRun

type HTMLRun struct {
	Properties *RunProperties
	Content    []HTMLRunElement
}

HTMLRun represents a single OOXML run with specific formatting

type HTMLRunElement

type HTMLRunElement struct {
	Type string // "text" or "break"
	Text string // for text elements
}

HTMLRunElement represents an element within a run (text or break)

type HTMLRuns

type HTMLRuns struct {
	Runs []HTMLRun
}

HTMLRuns represents a collection of OOXML runs generated from HTML

type Height

type Height = xml.Height

Re-export table types

type Hyperlink = xml.Hyperlink

Re-export paragraph types

func RenderHyperlinkWithContext

func RenderHyperlinkWithContext(hyperlink *Hyperlink, data TemplateData, ctx *renderContext) (*Hyperlink, error)

RenderHyperlinkWithContext renders a hyperlink with context

type IfNode

type IfNode struct {
	Condition ExpressionNode
	ThenBody  []ControlStructure
	ElseBody  []ControlStructure
	ElsIfs    []*ElsIfNode
}

IfNode represents an if statement

func (*IfNode) Render

func (n *IfNode) Render(data TemplateData) (string, error)

func (*IfNode) RenderWithContext

func (n *IfNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)

func (*IfNode) String

func (n *IfNode) String() string

type IncludeNode

type IncludeNode struct {
	FragmentName ExpressionNode
}

IncludeNode represents an include statement

func (*IncludeNode) Render

func (n *IncludeNode) Render(data TemplateData) (string, error)

func (*IncludeNode) RenderWithContext

func (n *IncludeNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)

func (*IncludeNode) String

func (n *IncludeNode) String() string

type Indentation

type Indentation = xml.Indentation

Re-export paragraph types

type IndexAccessNode

type IndexAccessNode struct {
	Object ExpressionNode
	Index  ExpressionNode
}

IndexAccessNode represents index access (obj[index])

func (*IndexAccessNode) Evaluate

func (n *IndexAccessNode) Evaluate(data TemplateData) (interface{}, error)

func (*IndexAccessNode) String

func (n *IndexAccessNode) String() string

type IssueSeverity

type IssueSeverity string

IssueSeverity indicates parser issue severity.

const (
	IssueSeverityError   IssueSeverity = "error"
	IssueSeverityWarning IssueSeverity = "warning"
)

type Kern

type Kern = xml.Kern

Re-export run types

type Lang

type Lang = xml.Lang

Re-export run types

type LinkReplacementMarker

type LinkReplacementMarker struct {
	URL string
}

LinkReplacementMarker marks a location where a link should be replaced

func (LinkReplacementMarker) String

func (l LinkReplacementMarker) String() string

type LiteralNode

type LiteralNode struct {
	Value interface{}
}

LiteralNode represents a literal value (string, number, boolean)

func (*LiteralNode) Evaluate

func (n *LiteralNode) Evaluate(data TemplateData) (interface{}, error)

func (*LiteralNode) String

func (n *LiteralNode) String() string

type LogLevel

type LogLevel int
const (
	LogDebug LogLevel = iota
	LogInfo
	LogWarn
	LogError
	LogOff
)

func (LogLevel) String

func (l LogLevel) String() string

type Logger

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

func GetLogger

func GetLogger() *Logger

func NewLogger

func NewLogger(w io.Writer, level LogLevel) *Logger

func WithField

func WithField(key string, value interface{}) *Logger

func WithFields

func WithFields(fields Fields) *Logger

func (*Logger) Debug

func (l *Logger) Debug(format string, args ...interface{})

func (*Logger) DebugExpression

func (l *Logger) DebugExpression(expr string, result interface{})

func (*Logger) DebugTemplate

func (l *Logger) DebugTemplate(template string, context interface{})

Debug helpers for template development

func (*Logger) Error

func (l *Logger) Error(format string, args ...interface{})

func (*Logger) Info

func (l *Logger) Info(format string, args ...interface{})

func (*Logger) IsDebugMode

func (l *Logger) IsDebugMode() bool

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...interface{})

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Logger

func (*Logger) WithFields

func (l *Logger) WithFields(fields Fields) *Logger

type MultiError

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

MultiError collects multiple errors

func NewMultiError

func NewMultiError() *MultiError

NewMultiError creates a new multi-error collector

func (*MultiError) Add

func (m *MultiError) Add(err error)

Add adds an error to the collection (ignores nil errors)

func (*MultiError) Err

func (m *MultiError) Err() error

Err returns the multi-error or nil if empty

func (*MultiError) Error

func (m *MultiError) Error() string

func (*MultiError) Len

func (m *MultiError) Len() int

Len returns the number of errors

type OOXMLFragment

type OOXMLFragment struct {
	Content interface{} // The OOXML content (e.g., Break, etc.)
}

OOXMLFragment represents a fragment of OOXML content to be inserted

type Option

type Option func(*Engine)

Option represents a configuration option for the engine.

func WithCache

func WithCache(maxSize int) Option

WithCache returns an option that sets the cache size (0 disables caching).

func WithConfig

func WithConfig(config *Config) Option

WithConfig returns an option that sets the engine configuration.

func WithFunction

func WithFunction(name string, fn Function) Option

WithFunction returns an option that registers a custom function.

func WithFunctionProvider

func WithFunctionProvider(provider FunctionProvider) Option

WithFunctionProvider returns an option that registers functions from a provider.

type Paragraph

type Paragraph = xml.Paragraph

Re-export paragraph types

func RenderParagraph

func RenderParagraph(para *Paragraph, data TemplateData) (*Paragraph, error)

RenderParagraph renders a paragraph

func RenderParagraphWithContext

func RenderParagraphWithContext(para *Paragraph, data TemplateData, ctx *renderContext) (*Paragraph, error)

RenderParagraphWithContext renders a paragraph with context

type ParagraphContent

type ParagraphContent = xml.ParagraphContent

Re-export core types and interfaces

type ParagraphProperties

type ParagraphProperties = xml.ParagraphProperties

Re-export paragraph types

type ParseError

type ParseError struct {
	Message  string
	Token    string
	Position int
}

ParseError represents an error during template parsing

func (*ParseError) Error

func (e *ParseError) Error() string

type PreparedTemplate

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

PreparedTemplate represents a compiled template ready for rendering. Use Prepare() or PrepareFile() to create an instance.

func Prepare

func Prepare(r io.Reader) (*PreparedTemplate, error)

Prepare loads and compiles a template from an io.Reader using the default engine.

func PrepareFile

func PrepareFile(path string) (*PreparedTemplate, error)

PrepareFile loads and compiles a template from a file path using the default engine.

func PrepareWithCache

func PrepareWithCache(path string) (*PreparedTemplate, error)

PrepareWithCache loads and compiles a template with caching support. This is a convenience function that uses the default engine.

func (*PreparedTemplate) AddFragment

func (pt *PreparedTemplate) AddFragment(name string, content string) error

AddFragment adds a text fragment that can be included in the template using the {{include "name"}} syntax.

Fragments are useful for reusable content like headers, footers, or standard paragraphs. The content should be plain text; it will be wrapped in appropriate DOCX structure automatically.

Example:

err := template.AddFragment("disclaimer", "This is confidential information.")
if err != nil {
    log.Fatal(err)
}

Then in your template: {{include "disclaimer"}}

func (*PreparedTemplate) AddFragmentFromBytes

func (pt *PreparedTemplate) AddFragmentFromBytes(name string, docxBytes []byte) error

AddFragmentFromBytes adds a DOCX fragment from raw bytes. This allows including pre-formatted DOCX content with styling, tables, etc. The fragment should be a complete DOCX file.

Example:

fragmentBytes, err := os.ReadFile("header.docx")
if err != nil {
    log.Fatal(err)
}
err = template.AddFragmentFromBytes("header", fragmentBytes)
if err != nil {
    log.Fatal(err)
}

Then in your template: {{include "header"}}

func (*PreparedTemplate) Close

func (pt *PreparedTemplate) Close() error

Close releases any resources held by the prepared template. After calling Close, the template should not be used.

func (*PreparedTemplate) Render

func (pt *PreparedTemplate) Render(data TemplateData) (io.Reader, error)

type ProofErr

type ProofErr = xml.ProofErr

Re-export paragraph types

type RawXMLElement

type RawXMLElement = xml.RawXMLElement

Re-export core types and interfaces

type Relationship

type Relationship struct {
	ID         string `xml:"Id,attr"`
	Type       string `xml:"Type,attr"`
	Target     string `xml:"Target,attr"`
	TargetMode string `xml:"TargetMode,attr,omitempty"`
}

Relationship represents a relationship in the DOCX package

type Relationships

type Relationships struct {
	XMLName      xml.Name       `xml:"Relationships"`
	Namespace    string         `xml:"xmlns,attr"`
	Relationship []Relationship `xml:"Relationship"`
}

Relationships represents the collection of relationships

type Run

type Run = xml.Run

Re-export run types

func RenderRun

func RenderRun(run *Run, data TemplateData) (*Run, error)

RenderRun renders a run of text

func RenderRunWithContext

func RenderRunWithContext(run *Run, data TemplateData, ctx *renderContext) (*Run, error)

RenderRunWithContext renders a run of text with context

type RunProperties

type RunProperties = xml.RunProperties

Re-export run types

type RunStyle

type RunStyle = xml.RunStyle

Re-export run types

type Shading

type Shading = xml.Shading

Re-export table types

type SimpleFunctionImpl

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

SimpleFunctionImpl provides a basic implementation of Function

func (*SimpleFunctionImpl) Call

func (f *SimpleFunctionImpl) Call(args ...interface{}) (interface{}, error)

func (*SimpleFunctionImpl) MaxArgs

func (f *SimpleFunctionImpl) MaxArgs() int

func (*SimpleFunctionImpl) MinArgs

func (f *SimpleFunctionImpl) MinArgs() int

func (*SimpleFunctionImpl) Name

func (f *SimpleFunctionImpl) Name() string

type Size

type Size = xml.Size

Re-export run types

type Spacing

type Spacing = xml.Spacing

Re-export paragraph types

type StencilIssueCode

type StencilIssueCode string

StencilIssueCode contains validation issue codes emitted by go-stencil.

const (
	IssueCodeSyntaxError          StencilIssueCode = "SYNTAX_ERROR"
	IssueCodeControlBlockMismatch StencilIssueCode = "CONTROL_BLOCK_MISMATCH"
	IssueCodeUnsupportedExpr      StencilIssueCode = "UNSUPPORTED_EXPRESSION"
	IssueCodeUnknownField         StencilIssueCode = "UNKNOWN_FIELD"
	IssueCodeUnknownFunction      StencilIssueCode = "UNKNOWN_FUNCTION"
	IssueCodeFunctionArgError     StencilIssueCode = "FUNCTION_ARGUMENT_ERROR"
	IssueCodeTypeMismatch         StencilIssueCode = "TYPE_MISMATCH"
)

type StencilMetadata

type StencilMetadata struct {
	DocumentHash       string `json:"documentHash"`
	TemplateRevisionID string `json:"templateRevisionId,omitempty"`
	ParserVersion      string `json:"parserVersion"`
}

StencilMetadata identifies parser metadata and request passthrough fields.

type StencilValidationIssue

type StencilValidationIssue struct {
	ID          string           `json:"id"`
	Severity    IssueSeverity    `json:"severity"`
	Code        StencilIssueCode `json:"code"`
	Message     string           `json:"message"`
	Token       TemplateTokenRef `json:"token"`
	Location    TemplateLocation `json:"location"`
	Suggestions []string         `json:"suggestions,omitempty"`
}

StencilValidationIssue is a validation issue emitted by go-stencil.

type StencilValidationSummary

type StencilValidationSummary struct {
	CheckedTokens      int `json:"checkedTokens"`
	ErrorCount         int `json:"errorCount"`
	WarningCount       int `json:"warningCount"`
	ReturnedIssueCount int `json:"returnedIssueCount"`
}

StencilValidationSummary contains validation counters.

type Style

type Style = xml.Style

Re-export core types and interfaces

type Styles

type Styles struct {
	XMLName   xml.Name        `xml:"styles"`
	Namespace string          `xml:"xmlns:w,attr"`
	Styles    []DocumentStyle `xml:"style"`
	RawXML    []byte          `xml:",innerxml"` // Store the raw XML
}

Styles represents the w:styles element in styles.xml

type Tab

type Tab = xml.Tab

Re-export paragraph types

type Table

type Table = xml.Table

Re-export table types

func FindTablesWithTemplates

func FindTablesWithTemplates(doc *Document) []*Table

FindTablesWithTemplates finds all tables that contain template expressions

func RenderTableWithControlStructures

func RenderTableWithControlStructures(table *Table, data TemplateData, ctx *renderContext) (*Table, error)

RenderTableWithControlStructures renders a table with support for loops and conditionals

type TableBorders

type TableBorders = xml.TableBorders

Re-export table types

type TableCell

type TableCell = xml.TableCell

Re-export table types

func RenderTableCell

func RenderTableCell(cell *TableCell, data TemplateData, ctx *renderContext) (*TableCell, error)

RenderTableCell renders a table cell

type TableCellBorders

type TableCellBorders = xml.TableCellBorders

Re-export table types

type TableCellMargins

type TableCellMargins = xml.TableCellMargins

Re-export table types

type TableCellProperties

type TableCellProperties = xml.TableCellProperties

Re-export table types

type TableColumnMarker

type TableColumnMarker struct {
	Action         string // "hide"
	ColumnIndex    int
	ResizeStrategy string // "redistribute", "proportional", "fixed", or empty for default
}

TableColumnMarker represents a marker for column operations

func (TableColumnMarker) String

func (m TableColumnMarker) String() string

String returns the string representation of the marker for rendering

type TableContext

type TableContext struct {
	TableIndex int    // Index of the table in the document
	Table      *Table // Pointer to the table
	RowIndex   int    // Current row being processed
	CellIndex  int    // Current cell being processed
	ColumnSpan int    // Column span of current cell
}

TableContext represents the context information for a table during processing

func NewTableContext

func NewTableContext(tableIndex int, table *Table) *TableContext

NewTableContext creates a new table context

func (*TableContext) CurrentCell

func (tc *TableContext) CurrentCell() *TableCell

CurrentCell returns the current cell being processed, or nil if not in a cell

func (*TableContext) EnterCell

func (tc *TableContext) EnterCell(cellIndex int)

EnterCell sets the context to process a specific cell

func (*TableContext) EnterRow

func (tc *TableContext) EnterRow(rowIndex int)

EnterRow sets the context to process a specific row

func (*TableContext) ExitCell

func (tc *TableContext) ExitCell()

ExitCell exits the current cell context

func (*TableContext) ExitRow

func (tc *TableContext) ExitRow()

ExitRow exits the current row context

func (*TableContext) IsInCell

func (tc *TableContext) IsInCell() bool

IsInCell returns true if we're currently processing within a table cell

func (*TableContext) IsInTable

func (tc *TableContext) IsInTable() bool

IsInTable returns true if we're currently processing within a table

type TableGrid

type TableGrid = xml.TableGrid

Re-export table types

type TableIndentation

type TableIndentation = xml.TableIndentation

Re-export table types

type TableInfo

type TableInfo struct {
	Index       int   // Index of the table in the document
	RowCount    int   // Number of rows
	ColumnCount int   // Number of columns (maximum across all rows)
	HasGrid     bool  // Whether the table has explicit column definitions
	GridWidths  []int // Column widths from table grid
}

TableInfo provides information about a table's structure

func GetTableInfo

func GetTableInfo(table *Table) *TableInfo

GetTableInfo analyzes a table and returns structural information

type TableLayout

type TableLayout = xml.TableLayout

Re-export table types

type TableLook

type TableLook = xml.TableLook

Re-export table types

type TableProperties

type TableProperties = xml.TableProperties

Re-export table types

type TableRow

type TableRow = xml.TableRow

Re-export table types

func RenderTableRow

func RenderTableRow(row *TableRow, data TemplateData, ctx *renderContext) (*TableRow, error)

RenderTableRow renders a single table row

type TableRowMarker

type TableRowMarker struct {
	Action string // "hide" for hideRow()
}

TableRowMarker represents a marker for table row operations

type TableRowProperties

type TableRowProperties = xml.TableRowProperties

Re-export table types

type Tabs

type Tabs = xml.Tabs

Re-export paragraph types

type TemplateCache

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

TemplateCache provides caching for prepared templates

func NewTemplateCache

func NewTemplateCache() *TemplateCache

NewTemplateCache creates a new template cache with default configuration

func NewTemplateCacheWithConfig

func NewTemplateCacheWithConfig(config CacheConfig) *TemplateCache

NewTemplateCacheWithConfig creates a new template cache with the given configuration

func (*TemplateCache) Clear

func (tc *TemplateCache) Clear()

Clear removes all templates from the cache and closes them

func (*TemplateCache) Close

func (tc *TemplateCache) Close() error

Close closes all templates in the cache and clears it

func (*TemplateCache) Get

func (tc *TemplateCache) Get(key string) (*PreparedTemplate, bool)

Get retrieves a template from cache without preparing a new one

func (*TemplateCache) Prepare

func (tc *TemplateCache) Prepare(reader io.Reader, key string) (*PreparedTemplate, error)

Prepare retrieves a template from cache or prepares a new one

func (*TemplateCache) Remove

func (tc *TemplateCache) Remove(key string)

Remove removes a template from the cache and closes it

func (*TemplateCache) Set

func (tc *TemplateCache) Set(key string, template *PreparedTemplate)

Set adds a template to the cache

func (*TemplateCache) Size

func (tc *TemplateCache) Size() int

Size returns the current number of cached templates

type TemplateData

type TemplateData map[string]interface{}

TemplateData represents the data context for rendering templates. It's a map of key-value pairs where values can be strings, numbers, booleans, slices, maps, or any other type that can be accessed in template expressions.

Example:

data := TemplateData{
    "name": "John Doe",
    "age": 30,
    "items": []map[string]interface{}{
        {"name": "Item 1", "price": 19.99},
        {"name": "Item 2", "price": 29.99},
    },
}

type TemplateError

type TemplateError struct {
	Message string
	Line    int
	Column  int
}

TemplateError represents an error in the template structure or syntax

func (*TemplateError) Error

func (e *TemplateError) Error() string

type TemplateLocation

type TemplateLocation struct {
	Part           string `json:"part"`
	ParagraphIndex int    `json:"paragraphIndex"`
	RunIndex       int    `json:"runIndex"`
	CharStartUTF16 int    `json:"charStartUtf16"`
	CharEndUTF16   int    `json:"charEndUtf16"`
	TokenOrdinal   int    `json:"tokenOrdinal"`
	AnchorID       string `json:"anchorId,omitempty"`
}

TemplateLocation identifies a token location in a DOCX part.

type TemplateTokenRef

type TemplateTokenRef struct {
	Raw        string           `json:"raw"`
	Kind       TokenKind        `json:"kind"`
	Expression string           `json:"expression,omitempty"`
	Location   TemplateLocation `json:"location"`
}

TemplateTokenRef references one token-derived item.

type TestTemplate

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

TestTemplate is a wrapper around the internal template type for testing

func Parse

func Parse(filename string, content string) (*TestTemplate, error)

Parse creates a test template from a string (for testing only)

func ParseBytes

func ParseBytes(docxBytes []byte) (*TestTemplate, error)

ParseBytes creates a test template from DOCX bytes (for testing only)

func (*TestTemplate) AddFragment

func (t *TestTemplate) AddFragment(name string, content string) error

AddFragment adds a text fragment that can be included using {{include "name"}}

func (*TestTemplate) AddFragmentFromBytes

func (t *TestTemplate) AddFragmentFromBytes(name string, docxBytes []byte) error

AddFragmentFromBytes adds a DOCX fragment from raw bytes

func (*TestTemplate) Close

func (t *TestTemplate) Close() error

Close releases resources held by the template

func (*TestTemplate) Render

func (t *TestTemplate) Render(data map[string]interface{}) (string, error)

Render renders the template with the given data (for simple text templates)

func (*TestTemplate) RenderToBytes

func (t *TestTemplate) RenderToBytes(data map[string]interface{}) ([]byte, error)

RenderToBytes renders the template to DOCX bytes

type Text

type Text = xml.Text

Re-export run types

func RenderText

func RenderText(text *Text, data TemplateData) (*Text, error)

RenderText renders text content with variable substitution

func RenderTextWithContext

func RenderTextWithContext(text *Text, data TemplateData, ctx *renderContext) (*Text, error)

RenderTextWithContext renders text content with variable substitution and context

type TextAlignment

type TextAlignment = xml.TextAlignment

Re-export paragraph types

type TextNode

type TextNode struct {
	Content string
}

TextNode represents plain text content

func (*TextNode) Render

func (n *TextNode) Render(data TemplateData) (string, error)

func (*TextNode) RenderWithContext

func (n *TextNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)

func (*TextNode) String

func (n *TextNode) String() string

type Token

type Token struct {
	Type  TokenType
	Value string
}

Token represents a parsed template token

func Tokenize

func Tokenize(input string) []Token

Tokenize parses a template string into tokens

type TokenKind

type TokenKind string

TokenKind identifies extracted token/reference categories.

const (
	TokenKindVariable TokenKind = "variable"
	TokenKindControl  TokenKind = "control"
	TokenKindFunction TokenKind = "function"
)

type TokenType

type TokenType int

TokenType represents the type of a template token

const (
	TokenText TokenType = iota
	TokenVariable
	TokenIf
	TokenElse
	TokenElsif
	TokenUnless
	TokenFor
	TokenEnd
	TokenPageBreak
	TokenInclude
)

type UnaryOpNode

type UnaryOpNode struct {
	Operator string
	Operand  ExpressionNode
}

UnaryOpNode represents a unary operation

func (*UnaryOpNode) Evaluate

func (n *UnaryOpNode) Evaluate(data TemplateData) (interface{}, error)

func (*UnaryOpNode) String

func (n *UnaryOpNode) String() string

type UnderlineStyle

type UnderlineStyle = xml.UnderlineStyle

Re-export run types

type UnlessNode

type UnlessNode struct {
	Condition ExpressionNode
	ThenBody  []ControlStructure
	ElseBody  []ControlStructure
}

UnlessNode represents an unless statement (negated if)

func (*UnlessNode) Render

func (n *UnlessNode) Render(data TemplateData) (string, error)

func (*UnlessNode) RenderWithContext

func (n *UnlessNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)

func (*UnlessNode) String

func (n *UnlessNode) String() string

type ValidateTemplateInput

type ValidateTemplateInput struct {
	DocxBytes          []byte           `json:"-"`
	TemplateRevisionID string           `json:"templateRevisionId,omitempty"`
	Strict             bool             `json:"strict,omitempty"`
	IncludeWarnings    bool             `json:"includeWarnings,omitempty"`
	MaxIssues          int              `json:"maxIssues,omitempty"` // 0 = unlimited
	Schema             ValidationSchema `json:"schema"`
}

ValidateTemplateInput controls full template validation behavior.

type ValidateTemplateResult

type ValidateTemplateResult struct {
	Valid           bool                     `json:"valid"`
	Summary         StencilValidationSummary `json:"summary"`
	Issues          []StencilValidationIssue `json:"issues"`
	IssuesTruncated bool                     `json:"issuesTruncated"`
	Metadata        StencilMetadata          `json:"metadata"`
}

ValidateTemplateResult contains full validation output.

func ValidateTemplate

func ValidateTemplate(input ValidateTemplateInput) (ValidateTemplateResult, error)

ValidateTemplate validates DOCX template syntax and semantics in a single call.

type ValidateTemplateSyntaxInput

type ValidateTemplateSyntaxInput struct {
	DocxBytes          []byte `json:"-"`
	TemplateRevisionID string `json:"templateRevisionId,omitempty"`
	MaxIssues          int    `json:"maxIssues,omitempty"` // 0 = unlimited
}

ValidateTemplateSyntaxInput controls syntax validation behavior.

type ValidateTemplateSyntaxResult

type ValidateTemplateSyntaxResult struct {
	Valid           bool                     `json:"valid"`
	Summary         StencilValidationSummary `json:"summary"`
	Issues          []StencilValidationIssue `json:"issues"`
	IssuesTruncated bool                     `json:"issuesTruncated"`
	Metadata        StencilMetadata          `json:"metadata"`
}

ValidateTemplateSyntaxResult contains syntax validation output.

func ValidateTemplateSyntax

func ValidateTemplateSyntax(input ValidateTemplateSyntaxInput) (ValidateTemplateSyntaxResult, error)

ValidateTemplateSyntax validates DOCX template syntax and control balance.

type ValidationSchema

type ValidationSchema struct {
	Fields    []FieldDefinition    `json:"fields"`
	Functions []FunctionDefinition `json:"functions"`
}

ValidationSchema contains field/function schema definitions used for semantic validation.

type VariableNode

type VariableNode struct {
	Name string
}

VariableNode represents a variable reference

func (*VariableNode) Evaluate

func (n *VariableNode) Evaluate(data TemplateData) (interface{}, error)

func (*VariableNode) String

func (n *VariableNode) String() string

type VerticalAlign

type VerticalAlign = xml.VerticalAlign

Re-export run types

type Width

type Width = xml.Width

Re-export table types

type XMLElement

type XMLElement struct {
	Type    string       // "element", "text", or "chardata"
	Name    xml.Name     // element name (for type="element")
	Attrs   []xml.Attr   // attributes (for type="element")
	Content []XMLElement // child elements (for type="element")
	Text    string       // text content (for type="text" or "chardata")
}

XMLElement represents a parsed XML element

type XMLFragment

type XMLFragment struct {
	Elements []XMLElement
}

XMLFragment represents a collection of XML elements from the xml() function

Directories

Path Synopsis
Package render provides helper functions for DOCX template rendering.
Package render provides helper functions for DOCX template rendering.
Package xml provides XML structure definitions and types for DOCX documents.
Package xml provides XML structure definitions and types for DOCX documents.

Jump to

Keyboard shortcuts

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