tmplz

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: May 4, 2024 License: MIT Imports: 9 Imported by: 0

README

TMPLZ

Recursive, Non-intrusive templates.

Rules

  • A Template can be defined on its own or in a group with others.
    • Templates defined together can reference each other.
  • Unused Variables are assumed to be literals.
  • A Variable clause begins with a Prefix(e.g. @).
    • A Variable clause may terminate with a Suffix(e.g. _).
    • Additional Prefixes increase the "depth" of the Variable.
    • Suffixes within a Variable can be used to escape the "depth".
  • Use Prefixes and Suffixes to create a Variable Graph.
Examples

All examples explicitly include the suffix even when it can be ignored. (Optional suffixes denoted )

  1. Zero Variables:
    • @ by itself is not a variable.
    • @_ evaluates to _.
  2. One Variable:
    • A standard template variable: @solo‗ -> {@solo_}.
  3. Two Variables:
    • Two standard variables one after the other: @one_@two‗ -> {@one_}{@two_}.
      • Assigning one does not affect the other.
    • A variable with a sub-variable: @one@two‗‗ -> {@one@two__{@two_}}.
      • Neither @one nor @one@two can be assigned to.
      • You must first assign @two and that will set the actual name of @one@two.
        • e.g. ["two" -> "123"] then @one@two__ becomes @one123_.

Documentation

Overview

Package tmplz provides a templating engine with nested variables and dynamic variable assignment. It includes utilities for handling templates.

Index

Constants

View Source
const (
	ALPHA_RUNE = '@'
	ALPHA      = "@"

	OMEGA_RUNE = '_'
	OMEGA      = "_"

	OMICRON_RUNE = '‗'
	OMICRON      = "‗"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Assignments

type Assignments map[string]any

Assignments holds key-value pairs for template variable assignments.

func (Assignments) Assign

func (a Assignments) Assign(key string, value any)

Assign sets a value for a key in Assignments. If the key already exists, its value is updated.

func (Assignments) AssignMap

func (a Assignments) AssignMap(kvps map[string]any)

AssignMap assigns multiple key-value pairs from a given map to the Assignments.

func (Assignments) AssignObj

func (a Assignments) AssignObj(obj any)

AssignObj uses the exported fields of the provided object to assign key-value pairs to the Assignments. Each field name is used as a key.

func (Assignments) Clone

func (a Assignments) Clone() Assignments

Clone creates a deep copy of the Assignments and returns it.

func (Assignments) Get

func (a Assignments) Get(key string) (String, bool)

Get retrieves the value associated with the given key as a String, and a boolean indicating if the key was found.

type MultiTemplate

type MultiTemplate struct {
	Templates map[string]*Template
}

func ParseTemplates

func ParseTemplates(templateMap map[string]string) *MultiTemplate

ParseTemplates is similar to ParseTemplates but includes logging support.

func (MultiTemplate) Clone

func (mt MultiTemplate) Clone() *MultiTemplate

Clone creates a deep copy of the MultiTemplate, including all its templates.

func (MultiTemplate) Debug

func (mt MultiTemplate) Debug() string

Debug returns a detailed string representation of all templates in MultiTemplate, including template names and their debug information.

func (MultiTemplate) Dot

func (mt MultiTemplate) Dot() string

Dot generates a Graphviz dot graph of the MultiTemplate, illustrating the relationships between templates.

func (MultiTemplate) Execute

func (mt MultiTemplate) Execute(assignments Assignments) (string, *MultiTemplate)

Execute clones the MultiTemplate and executes the Assignments on the clone.

Returns the result as well as the clone. By default, the result will be the value that has the key ".". If missing, an empty string is returned.

func (*MultiTemplate) ExecuteInPlace

func (mt *MultiTemplate) ExecuteInPlace(assignments Assignments) (anyChange bool)

ExecuteInPlace modifies the MultiTemplate using the data from the Assignments.

To select how "@_" gets evaluated, set:

assignments.Assign("", "_") // default value

Returns when no more assignments are left to assign.

func (MultiTemplate) String

func (mt MultiTemplate) String() string

String returns a string representation of all templates in MultiTemplate, formatted with indentation for readability. Each template's name and content are included.

type Node

type Node struct {
	// Parent points to the node's parent in the variable tree, if any.
	Parent *Node
	// Start is the index of the first character of the node text in the parent template.
	Start int
	// End is the index of the last character of the node text in the parent template.
	End int
	// Text contains the literal text of the node or the resolved value of a variable.
	Text String
	// Children holds any child nodes, representing nested variables.
	Children []*Node
}

Node represents a single variable or literal within a template. It can have child nodes, allowing for nested variable resolution.

func ParseNode

func ParseNode(s String) (*Node, string, error)

ParseNode is similar to ParseNode but with added logging functionality.

func (*Node) AppendAlpha

func (n *Node) AppendAlpha()

AppendAlpha adds the ALPHA_RUNE to the node's text, indicating the start of a variable.

func (*Node) AppendOmega

func (n *Node) AppendOmega(real bool)

AppendOmega adds the OMEGA_RUNE to the node's text, indicating the end of a variable.

func (*Node) AppendRunes

func (n *Node) AppendRunes(s ...rune)

AppendRunes adds runes to the node's text, updating the node and its ancestors accordingly.

func (Node) Clone

func (n Node) Clone() *Node

Clone creates a deep copy of the Node and its children.

func (Node) Debug

func (n Node) Debug() string

Debug returns a detailed string representation of the node, including indices and child nodes.

func (Node) DeepStart

func (n Node) DeepStart() int

DeepStart calculates the absolute start index of the node's text within the root template.

func (Node) Dot

func (n Node) Dot() string

Dot generates a Graphviz dot graph representation of the node and its children.

func (Node) Execute

func (n Node) Execute(assignments Assignments) (result string, clone *Node)

Execute clones the Node and executes the Assignments on the clone.

Returns the result as well as the clone.

func (*Node) ExecuteInPlace

func (n *Node) ExecuteInPlace(assignments Assignments) (anyChange bool)

ExecuteInPlace modifies the Node using the data from the Assignments.

To select how "@_" gets evaluated, set:

assignments.Assign("", "_") // default value

Returns when no more assignments are left to assign.

func (Node) String

func (n Node) String() string

String returns a string representation of the node and its children.

func (Node) Verify

func (n Node) Verify()

Verify checks the consistency of the node's text with its children's texts.

type ParseState

type ParseState struct {
	Tokens Tokens // Tokens represents the lexed tokens of the template string.
	Cursor int    // Cursor represents the current position in the token slice.
}

ParseState represents the state of parsing a template string, tracking tokens and cursor position.

func NewState

func NewState(s string) *ParseState

NewState initializes a new ParseState for parsing a template string.

func (ParseState) Debug

func (s ParseState) Debug() string

Debug returns a detailed string representation of the parse state, indicating the cursor position.

func (ParseState) NextToken

func (s ParseState) NextToken() Token

NextToken returns the next token in the sequence, or EOF if at the end.

func (*ParseState) Parse

func (s *ParseState) Parse(from int, root *Node) (*Node, int, error)

Parse processes tokens from the current cursor position to construct a Node tree.

func (ParseState) PeekNext

func (s ParseState) PeekNext(kind TokenKind) (int, bool)

PeekNext searches for the next occurrence of a token of the specified kind and returns its position.

func (ParseState) String

func (s ParseState) String() string

String returns a string representation of the current parse state, including tokens.

type String

type String = stringutil.String

type Template

type Template struct {
	Text     String
	Children []*Node
}

func ParseTemplate

func ParseTemplate(s string) *Template

ParseTemplate is similar to ParseTemplate but includes logging support for parsing.

func (Template) Clone

func (t Template) Clone() *Template

Clone creates a deep copy of the Template, including all child nodes.

func (Template) Debug

func (t Template) Debug() string

Debug returns a detailed string representation of the template for debugging purposes.

func (Template) Dot

func (t Template) Dot() string

Dot generates a Graphviz dot graph representation of the template and its variables.

func (Template) Execute

func (t Template) Execute(assignments Assignments) (result string, clone *Template)

Execute clones the Node and executes the Assignments on the clone.

Returns the result as well as the clone.

func (*Template) ExecuteInPlace

func (t *Template) ExecuteInPlace(assignments Assignments) (anyChange bool)

ExecuteInPlace modifies the Template using the data from the Assignments.

To select how "@_" gets evaluated, set:

assignments.Assign("", "_") // default value

Returns when no more assignments are left to assign.

func (Template) String

func (t Template) String() string

String returns a string representation of the template, including its text and variables.

func (Template) Verify

func (t Template) Verify()

Verify checks the consistency of the template's text with its nodes.

type Token

type Token struct {
	Kind TokenKind
	Rune rune
	Pos  int
}

Token defines a lexical token with its kind, rune, and position in the input string.

func (Token) String

func (t Token) String() string

String returns a string representation of the Token, including its rune and position.

type TokenKind

type TokenKind uint

TokenKind represents the type of lexical token identified in template strings.

const (
	TokenEOF   TokenKind = 0
	TokenAlpha TokenKind = 1 << (iota - 1)
	TokenOmega
	TokenNumber
	TokenLetter
	TokenSpace
	TokenUnknown
)

type Tokens

type Tokens []Token

Tokens is a slice of Token instances, representing a sequence of tokens lexed from a template string.

func Lex

func Lex(s String) (result Tokens)

Lex performs lexical analysis on the input string, identifying and categorizing each rune as a token based on its type (e.g., letter, number, special rune). Returns a slice of Tokens representing the lexed input.

func (Tokens) String

func (ts Tokens) String() string

String returns a concatenated string representation of all Tokens in the slice.

Jump to

Keyboard shortcuts

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