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
- Variables
- func CallFunction(name string, data TemplateData, args ...interface{}) (interface{}, error)
- func ClearCache()
- func Debug(format string, args ...interface{})
- func Error(format string, args ...interface{})
- func EvaluateBinaryOperation(left interface{}, operator string, right interface{}) (interface{}, error)
- func EvaluateVariable(expression string, data TemplateData) (interface{}, error)
- func FindTemplateTokens(input string) []string
- func FormatValue(value interface{}) string
- func Info(format string, args ...interface{})
- func NewDocumentError(operation, path string, cause error) error
- func NewEvaluationError(expression string, cause error) error
- func NewFunctionError(function string, args []interface{}, message string) error
- func NewParseError(message, token string, position int) error
- func NewTemplateError(message string, line, column int) error
- func ProcessTableColumnMarkers(doc *Document) error
- func ProcessTableRowMarkers(doc *Document) error
- func ProcessTemplateWithFragments(content string, data TemplateData, fragments map[string]*fragment) (string, error)
- func RegisterFunctionsFromProvider(provider FunctionProvider) error
- func RegisterGlobalFunction(name string, fn Function) error
- func SetCacheConfig(maxSize int, ttl time.Duration)
- func SetGlobalConfig(config *Config)
- func SetLogger(logger *Logger)
- func UpdateLoggerFromConfig()
- func Warn(format string, args ...interface{})
- func WithContext(err error, operation string, context map[string]interface{}) error
- type Alignment
- type BinaryOpNode
- type Body
- type BodyElement
- type BorderProperties
- type Break
- type CacheConfig
- type CellMargin
- type Color
- type Config
- type ContentTypeDefault
- type ContentTypeOverride
- type ContentTypes
- type ContextError
- type ControlParser
- type ControlStructure
- type DefaultFunctionRegistry
- type Document
- type DocumentError
- type DocumentPart
- type DocumentStyle
- type DocxReader
- func (dr *DocxReader) GetDocumentXML() (string, error)
- func (dr *DocxReader) GetPart(partName string) ([]byte, error)
- func (dr *DocxReader) GetRelationships(partName string) ([]Relationship, error)
- func (dr *DocxReader) GetRelationshipsXML() (string, error)
- func (dr *DocxReader) ListParts() []string
- type ElementWithPath
- type ElsIfNode
- type Empty
- type Engine
- func (e *Engine) ClearCache()
- func (e *Engine) Close() error
- func (e *Engine) Config() *Config
- func (e *Engine) Prepare(r io.Reader) (*PreparedTemplate, error)
- func (e *Engine) PrepareFile(path string) (*PreparedTemplate, error)
- func (e *Engine) RegisterFunction(name string, fn Function) error
- func (e *Engine) RegisterFunctionsFromProvider(provider FunctionProvider) error
- func (e *Engine) SetConfig(config *Config)
- type EvaluationError
- type ExpressionContentNode
- type ExpressionNode
- type ExpressionParser
- type ExpressionToken
- type ExpressionTokenType
- type ExtractReferencesInput
- type ExtractReferencesResult
- type FieldAccessNode
- type FieldDefinition
- type Fields
- type Font
- type ForNode
- type Function
- type FunctionCallNode
- type FunctionDefinition
- type FunctionError
- type FunctionProvider
- type FunctionRegistry
- type GridColumn
- type GridSpan
- type HTMLNode
- type HTMLRun
- type HTMLRunElement
- type HTMLRuns
- type Height
- type Hyperlink
- type IfNode
- type IncludeNode
- type Indentation
- type IndexAccessNode
- type IssueSeverity
- type Kern
- type Lang
- type LinkReplacementMarker
- type LiteralNode
- type LogLevel
- type Logger
- func (l *Logger) Debug(format string, args ...interface{})
- func (l *Logger) DebugExpression(expr string, result interface{})
- func (l *Logger) DebugTemplate(template string, context interface{})
- func (l *Logger) Error(format string, args ...interface{})
- func (l *Logger) Info(format string, args ...interface{})
- func (l *Logger) IsDebugMode() bool
- func (l *Logger) SetLevel(level LogLevel)
- func (l *Logger) Warn(format string, args ...interface{})
- func (l *Logger) WithField(key string, value interface{}) *Logger
- func (l *Logger) WithFields(fields Fields) *Logger
- type MultiError
- type OOXMLFragment
- type Option
- type Paragraph
- type ParagraphContent
- type ParagraphProperties
- type ParseError
- type PreparedTemplate
- type ProofErr
- type RawXMLElement
- type Relationship
- type Relationships
- type Run
- type RunProperties
- type RunStyle
- type Shading
- type SimpleFunctionImpl
- type Size
- type Spacing
- type StencilIssueCode
- type StencilMetadata
- type StencilValidationIssue
- type StencilValidationSummary
- type Style
- type Styles
- type Tab
- type Table
- type TableBorders
- type TableCell
- type TableCellBorders
- type TableCellMargins
- type TableCellProperties
- type TableColumnMarker
- type TableContext
- type TableGrid
- type TableIndentation
- type TableInfo
- type TableLayout
- type TableLook
- type TableProperties
- type TableRow
- type TableRowMarker
- type TableRowProperties
- type Tabs
- type TemplateCache
- func (tc *TemplateCache) Clear()
- func (tc *TemplateCache) Close() error
- func (tc *TemplateCache) Get(key string) (*PreparedTemplate, bool)
- func (tc *TemplateCache) Prepare(reader io.Reader, key string) (*PreparedTemplate, error)
- func (tc *TemplateCache) Remove(key string)
- func (tc *TemplateCache) Set(key string, template *PreparedTemplate)
- func (tc *TemplateCache) Size() int
- type TemplateData
- type TemplateError
- type TemplateLocation
- type TemplateTokenRef
- type TestTemplate
- func (t *TestTemplate) AddFragment(name string, content string) error
- func (t *TestTemplate) AddFragmentFromBytes(name string, docxBytes []byte) error
- func (t *TestTemplate) Close() error
- func (t *TestTemplate) Render(data map[string]interface{}) (string, error)
- func (t *TestTemplate) RenderToBytes(data map[string]interface{}) ([]byte, error)
- type Text
- type TextAlignment
- type TextNode
- type Token
- type TokenKind
- type TokenType
- type UnaryOpNode
- type UnderlineStyle
- type UnlessNode
- type ValidateTemplateInput
- type ValidateTemplateResult
- type ValidateTemplateSyntaxInput
- type ValidateTemplateSyntaxResult
- type ValidationSchema
- type VariableNode
- type VerticalAlign
- type Width
- type XMLElement
- type XMLFragment
Constants ¶
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 ¶
var DefaultEngine = New()
DefaultEngine is the global default engine instance. It uses the global configuration and function registry.
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 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 ¶
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 NewDocumentError ¶
NewDocumentError creates a new document error
func NewEvaluationError ¶
NewEvaluationError creates a new evaluation error
func NewFunctionError ¶
NewFunctionError creates a new function error
func NewParseError ¶
NewParseError creates a new parse error
func NewTemplateError ¶
NewTemplateError creates a new template error with position information
func ProcessTableColumnMarkers ¶
ProcessTableColumnMarkers processes column markers in the document
func ProcessTableRowMarkers ¶
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 ¶
RegisterGlobalFunction adds a custom function to the global function registry.
func SetCacheConfig ¶
SetCacheConfig updates the global cache configuration.
func SetGlobalConfig ¶
func SetGlobalConfig(config *Config)
SetGlobalConfig sets the global configuration
func UpdateLoggerFromConfig ¶
func UpdateLoggerFromConfig()
UpdateLoggerFromConfig updates the global logger based on the current global configuration
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 ¶
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 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 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 GetGlobalConfig ¶
func GetGlobalConfig() *Config
GetGlobalConfig returns the global configuration
func NewConfigWithDefaults ¶
NewConfigWithDefaults creates a new configuration with defaults applied to unset fields
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 NewWithConfig ¶
NewWithConfig creates a new template engine with custom configuration.
func NewWithOptions ¶
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) 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 ¶
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.
type EvaluationError ¶
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 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) RenderWithContext ¶
func (n *ForNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)
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
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 ¶
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 HTMLRun ¶
type HTMLRun struct {
Properties *RunProperties
Content []HTMLRunElement
}
HTMLRun represents a single OOXML run with specific formatting
type HTMLRunElement ¶
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 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) RenderWithContext ¶
func (n *IfNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)
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 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 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 Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
func WithFields ¶
func (*Logger) DebugExpression ¶
func (*Logger) DebugTemplate ¶
Debug helpers for template development
func (*Logger) IsDebugMode ¶
func (*Logger) WithFields ¶
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
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 WithConfig ¶
WithConfig returns an option that sets the engine configuration.
func WithFunction ¶
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 ¶
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 ¶
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 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 ¶
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 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 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 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 Table ¶
Re-export table types
func FindTablesWithTemplates ¶
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 TableCell ¶
Re-export table types
func RenderTableCell ¶
func RenderTableCell(cell *TableCell, data TemplateData, ctx *renderContext) (*TableCell, error)
RenderTableCell renders a table cell
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 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 ¶
GetTableInfo analyzes a table and returns structural information
type 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 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 ¶
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 ¶
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 TextNode ¶
type TextNode struct {
Content string
}
TextNode represents plain text content
func (*TextNode) RenderWithContext ¶
func (n *TextNode) RenderWithContext(data TemplateData, ctx *renderContext) (string, error)
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 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 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
Source Files
¶
- api.go
- cache.go
- config.go
- control.go
- date_functions.go
- doc.go
- docx.go
- errors.go
- eval.go
- expression.go
- fragment.go
- fragment_fonts.go
- fragment_resources.go
- functions.go
- html_functions.go
- link.go
- link_functions.go
- link_processing.go
- logger.go
- number_format_functions.go
- numbering.go
- render.go
- render_docx.go
- stencil.go
- styles.go
- table.go
- table_column_operations.go
- table_merge.go
- table_row_operations.go
- test_helpers.go
- tokenizer.go
- validation.go
- xml.go
- xml_fix.go
- xml_functions.go
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. |