itemcontrol

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2023 License: MIT Imports: 7 Imported by: 0

README

toolkit/template/itemcontrol

This packages provides interfaces and implementation for parsing elements of templates.

It is part of toolkit/template; Use it's information on installation for more information

Documentation

Overview

Package itemcontrol implements the logic needed for the different parsed tokens on a certain template. It is used by and written for git.dresden.micronet24.de/toolkit/template.

The approach of itemcontrol is to provide an interface to create a logic (for generating output documents algorithmically) at runtime based on creating and binding a certain amount of items. When all of these items are created, they can be compiled into a list of template functions and values, which can be used to create the output document by evaluating some data given by the user.

Items

There are a lot of different types of Items for different purposes. Each of the Items implement either ItemControlSingle, ItemControlMulti or ItemControlValue which all implement the interface ItemControl. The Items are usually of type `...Item` and have a corressponding function `Create...Item()` to generate a new instance.

Some items can also incorporate other items, which allows for conditionals and loops.

All items are used to collect all given information during the parsing process. After that process is done, while calling [ItemControlSingle.FuncContent], [ItemControlMulti.Content] or [ItemControlValue.Value] the item is "compiled" all unneeded information is discarded or contained within the template function returned. The items are not needed after this point

template functions

After compilation the parsed template is represented by a list of TmplFunc, which can be executed in order to generate the output document.

As some information within a template may not produce output but will represent some kind of value (with a given type), ItemControlValue items will generate TmplValue instead, which can be converted to TmplFunc using RenderValue, but these values still have the type information and can be handled by other items more efficiently.

Only the template functions will be provided with the data provided by the user and should not remember states between different calls (so that it is possible to use the same function instance with different userdata to create multiple documents)

Example

Create and execute a template.

// Item generation
iterator := CreateSequenceIteratorItem(5)
items := CreateValueLoopItem(iterator, CreateListItem().Append(CreateTextItem("\nIteration: ")).Append(iterator))

// compilation
funcs, err := GetMultiContent(items)
if err != nil {
	fmt.Fprintf(os.Stderr, "Compilation error: %s", err)
	return
}

// execution
if err = RunTmplFuncs(funcs, os.Stdout, nil); err != nil {
	fmt.Fprintf(os.Stderr, "Cannot execute template: %s", err)
	return
}
Output:


Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

Index

Examples

Constants

View Source
const (
	// FTGenerate is active for functions, which just generate a result
	FTGenerate = (FuncType)(1 << iota)

	// FTFilter is active for filtering functions (input is given as first arg)
	FTFilter

	// FTDefault marks functions, which are provided by default
	FTDefault
)
View Source
const (
	LoopContinue = (loopControl)(iota) // Loop should continue with next iteration
	LoopBreak                          // Loop execution should be terminated
)
View Source
const (
	ScopeMayDeclare     = (ItemScopeSet)(iota) // item may exist (will be overwritten), but will be declared otherwise
	ScopeMustDeclare                           // item must not exist
	ScopeMustNotDeclare                        // item must exist previously
	ScopeIgnoreIfExist                         // item may exist and will be left untouched, if so
)

Variables

This section is empty.

Functions

func Check

func Check(i ItemControl, MustExist bool) error

Check lets an ItemControl check itself.

If MustExist is given, the item may not be nil.

This is a convinience wrapper to easily check ItemControls, even if ItemControlCheckable isn't implemented

func ContentIndicateError

func ContentIndicateError(err error) (reflect.Value, error)

ContentIndicateError is a error-handler for ContentItem, indicating all errors

func ContentSupressError

func ContentSupressError(err error) (reflect.Value, error)

ContentSupressError is a error-handler for ContentItem, supressing any errors

func GetLengthContent

func GetLengthContent(i ItemControl) int

GetLengthContent counts the number of TmplFunc generated by the corresponding item, without actually compiling them.

func MustFunc

func MustFunc(fn any, err error) any

MustFunc can be used as Wrapper around Lookup, which will panic, if an error occurs

func RunTmplFuncs

func RunTmplFuncs(fs []TmplFunc, out io.Writer, val interface{}) error

RunTmplFuncs will call of the compiled functions fs with the userdata val and write the result to the writer out

func SelectOnMissingError

func SelectOnMissingError(name string, e error) (reflect.Value, error)

func SelectOnMissingIgnore

func SelectOnMissingIgnore(name string, e error) (reflect.Value, error)

Types

type AbsPosition

type AbsPosition struct {
	FName string
	// contains filtered or unexported fields
}

AbsPosition is a absolute Position within some File.

the default implementation of a PositionFile.

func (*AbsPosition) Column

func (p *AbsPosition) Column() int

Column returns the position in the current line

func (*AbsPosition) Create

func (p *AbsPosition) Create(name string) *AbsPosition

Create (re-)initiliazes a given Position for a (file-)name

func (*AbsPosition) Line

func (p *AbsPosition) Line() int

Line returns the line-number of the current position

func (*AbsPosition) Name

func (p *AbsPosition) Name() string

Name returns the (file-)name of the current Posiotn

func (*AbsPosition) Set

func (p *AbsPosition) Set(l, c int) PositionFile

Set updates the position of the current item

func (*AbsPosition) SetName

func (p *AbsPosition) SetName(name string)

SetName updates the (file-)name of the current Position

func (*AbsPosition) String

func (p *AbsPosition) String() string

String generates a parseable and human-readable string of the current position

func (*AbsPosition) Update

func (p *AbsPosition) Update(msg string)

type BasePosItem

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

BasePosItem is the default implementation for an ItemControl.

This will just perform position and error-handling

func (*BasePosItem) Errorf

func (b *BasePosItem) Errorf(errorFormat string, a ...interface{}) error

Errorf creates an error string containing the current items position

func (*BasePosItem) GetPosition

func (b *BasePosItem) GetPosition() string

GetPosition returns the human readable position of the current item (within the parsed file)

func (*BasePosItem) PosError

func (b *BasePosItem) PosError(err error) error

PosError appends position information to the error err, if it does not have one yet

func (*BasePosItem) Position

func (b *BasePosItem) Position() Position

Position returns the Position itself

func (*BasePosItem) RegisterLoop

func (b *BasePosItem) RegisterLoop(l ItemControl, depth int) error

RegisterLoop is a NOP-implementation and may be implemented by ItemControls, which depend on surrounding loop information

func (*BasePosItem) SetPosition

func (b *BasePosItem) SetPosition(pos Position)

SetPosition set's the position of the current item to the place specified by pos

type ConditionalItem

type ConditionalItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

A ConditionalItem represents a (list of) conditions and blocks, which are to be executed, when the condition is true

This can be used to implement if-else- or switch-case-blocks.

Each of the list of conditions is evaluated in order and the first returning true will have its corresponding block being executed. If none of the conditions evaluate to true, the elseblock is executed

func CreateConditionalItem

func CreateConditionalItem(test ItemControlValue, block *ItemControlList) *ConditionalItem

CreateConditionalItem will create a new Conditional Item with at least one condition and corresponding block to execute.

func (*ConditionalItem) Append

Append will append another ConditionalItem to the current one.

the conditions will be added at the end of the current block of conditionals (only testing them, if no further condition was true); the elseblock will be appended to the current elseblock (executing all items, if none of the conditions from the current or the other ConditionalItem becomes true)

the object itself is returned to support chained initialization

func (*ConditionalItem) AppendCondition

func (i *ConditionalItem) AppendCondition(test ItemControlValue, block *ItemControlList) *ConditionalItem

AppendCondition will append a new test and block to the ConditionalItem

the block will only be executed, if the new test is the first to be evaluated to true after the template is compiled.

the object itself is returned to support chained initialization

func (*ConditionalItem) AppendElse

func (i *ConditionalItem) AppendElse(block *ItemControlList) *ConditionalItem

AppendElse will append the given block to the ConditionalItem to be executed when no condition evaluate to true

the object itself is returned to support chained initialization

func (*ConditionalItem) Check

func (i *ConditionalItem) Check() error

Check will forward the Checkable request to all embedded conditions and block elements

func (*ConditionalItem) Create

func (i *ConditionalItem) Create() *ConditionalItem

Create will (re-)initialize the conditional block completely

it returns itself to support chained initialization

func (*ConditionalItem) FuncContent

func (i *ConditionalItem) FuncContent() (TmplFunc, error)

FuncContent will generate the TmplFunc for the conditional block execution

this implements a ItemControlSingle

func (*ConditionalItem) RegisterLoop

func (i *ConditionalItem) RegisterLoop(l ItemControl, depth int) error

RegisterLoop will forward the loop registration to all embedded elements

type ConstPosition

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

ConstPosition is a Position, that cannot be changed after creation.

func CopyPosition

func CopyPosition(src Position) *ConstPosition

CopyPosition copies a position, making the copy const

func CreatePositionOffset

func CreatePositionOffset(start, offset Position) *ConstPosition

CreatePositionOffset will create a ConstPosition by adding the one Position as offset to another Position start.

func (*ConstPosition) Column

func (p *ConstPosition) Column() int

func (*ConstPosition) CreateCopy

func (p *ConstPosition) CreateCopy(src Position) *ConstPosition

func (*ConstPosition) CreateOffset

func (p *ConstPosition) CreateOffset(start, offset Position) *ConstPosition

func (*ConstPosition) Line

func (p *ConstPosition) Line() int

func (*ConstPosition) Name

func (p *ConstPosition) Name() string

func (*ConstPosition) String

func (p *ConstPosition) String() string

String generates a parseable and human-readable string of the current position

type ContentFunctionGet

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

ContentFunctionGet implements a GetContent to provide a function-call as Content.

The function must return either * one value - which will be used value within the ContentItem * a value and an error - where the error will be returned, if not nil

func CreateFunctionGetter

func CreateFunctionGetter(fn interface{}, parm ...ItemControlValue) (*ContentFunctionGet, error)

CreateFunctionGetContent generates a new ContentGetFunction.

func (*ContentFunctionGet) Call

func (f *ContentFunctionGet) Call(fnp interface{}, v ...reflect.Value) (ret reflect.Value, err error)

Call will execute the function with the given parameters

func (*ContentFunctionGet) Create

func (f *ContentFunctionGet) Create(fn interface{}, addParm int, parm ...ItemControlValue) error

Create (re-)initializes the ContentFunction

if fn isn't a function with valid return values, an error is returned

func (*ContentFunctionGet) GetFunction

func (f *ContentFunctionGet) GetFunction(v interface{}) (reflect.Value, error)

GetFunction returns the value's content, to implement the GetContent interface

type ContentFunctionSelect

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

ContentFunctionSelect implements a SelectContent to filter a Content using a user-supplied function-call

The requirements for function return values are the same as for ContentFunctionGet

func CreateFunctionSelector

func CreateFunctionSelector(fn interface{}, parm ...ItemControlValue) (*ContentFunctionSelect, error)

CreateFunctionSelectContent generates a new ContentSelectFunction.

func (*ContentFunctionSelect) Call

func (f *ContentFunctionSelect) Call(fnp interface{}, v ...reflect.Value) (ret reflect.Value, err error)

Call will execute the function with the given parameters

func (*ContentFunctionSelect) Create

func (f *ContentFunctionSelect) Create(fn interface{}, addParm int, parm ...ItemControlValue) error

Create (re-)initializes the ContentFunction

if fn isn't a function with valid return values, an error is returned

func (*ContentFunctionSelect) SelectFunction

func (f *ContentFunctionSelect) SelectFunction(ud interface{}, v reflect.Value) (reflect.Value, error)

SelectFunction returns the value's filtered content, to implement the SelectContent interface

type ContentItem

type ContentItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

A ContentItem handles the process of selecting, filtering, getting and setting content into variables

See also ItemScope to manage the scope of variables; the result of ItemScope.Get would be the starting point for the ContentItem.

The process accessing a value within a template can be split into the followin steps:

1. getting the base variable (eg. userdata or some name specified within the template) 2. optionally selecting an element within a complex structure (eg. accessing array index or a map element) 3. optionally repeating the 2nd step for deeply structured date 4. rendering the result (or setting a new value, or ...)

All of these steps can be handled within a single ContentItem using some helper functionality.

func CreateContentItem

func CreateContentItem() *ContentItem

CreateContentItem will create a new item with default getter and renderer

func (*ContentItem) AddSelector

func (c *ContentItem) AddSelector(f SelectContent) *ContentItem

AddSelector will add a new selector, which will be executed after the getter.

func (*ContentItem) Check

func (c *ContentItem) Check() error

Check will assure a completely configured ContentItem

it will esp. test, wether a getter and renderer is set. If it isn't, you most probably didn't used the provided Create() interface

func (*ContentItem) Create

func (c *ContentItem) Create() *ContentItem

Create will (re-)initialize a ContentItem with default Getter and Renderer as described in ContentItem.GetFunction and ContentItem.RenderFunction

func (*ContentItem) FuncContent

func (c *ContentItem) FuncContent() (TmplFunc, error)

FuncContent will render the Content, performing the whole chain of content retrieval

func (*ContentItem) GetFunction

func (c *ContentItem) GetFunction(v interface{}) (reflect.Value, error)

GetFunction implements the default getter, which is to use the data, provided by the user for rendering the template

With this, ContentItem implements GetContent itself

func (*ContentItem) RenderFunction

func (c *ContentItem) RenderFunction(w io.Writer, v reflect.Value) error

RenderFunction implements the default renderer, which is to write the value to the output (using Printf's %v)

With this, ContentItem implements RenderContent itself

func (*ContentItem) SetErrorHandler

func (c *ContentItem) SetErrorHandler(hdl OnErrorHdl) *ContentItem

SetErrorHandler overwrites the current error handler for this ContentItem

func (*ContentItem) SetGetter

func (c *ContentItem) SetGetter(f GetContent) *ContentItem

SetGetter will set a new getter function for the content

func (*ContentItem) SetRender

func (c *ContentItem) SetRender(f RenderContent) *ContentItem

SetRenderer will set a new render function

func (*ContentItem) Value

func (c *ContentItem) Value() (TmplValue, error)

Value will get and select the content, but will not perform the rendering set.

type ContentSelection

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

ContentSelection implements SelectContent and can be added to a ContentItem to select a named item from the current object.

Depending on the type of the active item, the name will be handled differently.

  • For a struct or map, the name will specify the corresponding subelement,
  • For an interface, the name will test, wether a function of this name exists and call this (without arguments)
  • For a slice or an array, name should be convertable to an integer, indexing the object
  • For a complex 'R', 'Real', 'I' or 'Imag' can be used to select the real or complex part of that number

func CreateSelector

func CreateSelector(n string) *ContentSelection

CreateSelector will create a ContentSelection with a given name n

func (*ContentSelection) Create

func (sel *ContentSelection) Create(n string) *ContentSelection

Create will (re-)initialize the ContentSelection with a given name n

func (*ContentSelection) SelectFunction

func (sel *ContentSelection) SelectFunction(ud interface{}, v reflect.Value) (reflect.Value, error)

SelectFunction will perform the content selection

func (*ContentSelection) SetOnMissing

func (sel *ContentSelection) SetOnMissing(fn SelectOnMissingHdl) *ContentSelection

Set the OnMissing handler. Ignore by default

type ContentStatic

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

ContentStatic implements a GetContent to provide a static variable to ContentItem

func CreateStaticContent

func CreateStaticContent(v interface{}) *ContentStatic

CreateStaticContent creates a new ContentStatic with the given value

func (*ContentStatic) Create

func (c *ContentStatic) Create(v interface{}) *ContentStatic

Create (re-)initialize the ContentStatic

func (*ContentStatic) GetFunction

func (c *ContentStatic) GetFunction(v interface{}) (reflect.Value, error)

GetFunction returns the static content, to implement the GetContent interface

type ContentValue

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

ContentValue implements a GetContent to provide a ItemControlValue to ContentItem

func CreateValueContent

func CreateValueContent(v ItemControlValue) (*ContentValue, error)

CreateValueContent creates a new ContentValue with the given value

func (*ContentValue) Create

Create (re-)initialize the ContentValue

func (*ContentValue) GetFunction

func (c *ContentValue) GetFunction(v interface{}) (reflect.Value, error)

GetFunction returns the value's content, to implement the GetContent interface

type EmptyItem

type EmptyItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

The EmptyItem is known to have no content, but it implements ItemContentStripper

func CreateDummyItem

func CreateDummyItem() *EmptyItem

func CreateEmptyItem

func CreateEmptyItem(isStart, strip, dontstrip, stripdefault bool) *EmptyItem

CreateEmptyItem creates a new EmptyItem without content

isStart tells the item, wether the predecessor should be stripped. strip tells, wether striping is requested. dontstrip tells, wether striping is prohibited stripdefault decides, wether striping is enabled, when neither strip nor dontstrip are set. if strip and dontstrip are set, striping will be disabled

func (*EmptyItem) Content

func (e *EmptyItem) Content() ([]TmplFunc, error)

Content returns an empty array

func (*EmptyItem) Create

func (e *EmptyItem) Create(isStart, strip, dontstrip, stripdefault bool) *EmptyItem

Create (re-)initializes the Emptyitem

func (*EmptyItem) FuncContent

func (e *EmptyItem) FuncContent() (TmplFunc, error)

FuncContent implements the ItemControlSingle interface and writes nothing

func (*EmptyItem) IsStart

func (e *EmptyItem) IsStart() bool

Check, wether the EmptyElement is a StartElement (and looks for a later item)

func (*EmptyItem) Length

func (e *EmptyItem) Length() int

Length will always signal 0 elements (empty)

func (*EmptyItem) Strip

func (e *EmptyItem) Strip(pred bool) bool

Strip returns, wether the surrounding element should be stripped

func (*EmptyItem) Value

func (e *EmptyItem) Value() (TmplValue, error)

Value implements the ItemControlValue interface and returnes the invalid element

type FuncEntry

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

FuncEntry represents a Function within the Manager

type FuncLookup

type FuncLookup func(typ FuncType, name string) (any, error)

FuncLookup is a signature for a Lookup, as implemented by FuncManager

type FuncManager

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

FuncManager manages the set of known functions with their corresponding scopes

func CreateFuncManager

func CreateFuncManager() *FuncManager

CreateFuncManager creates and initializes an empty FuncManager

func (*FuncManager) Add

func (m *FuncManager) Add(name string, fn any, typ FuncType)

Add registers a new function implementation for a given name with a certain type

func (*FuncManager) Delete

func (m *FuncManager) Delete(typ FuncType, name string) error

Delete will drop previously added functions

func (*FuncManager) Filter

func (m *FuncManager) Filter(typ FuncType, name string) map[string]any

Filter will provide a map with all function matching the given type (at least one) and (part of) name as provided in the arguments.

If Zero/Empty is passed, no filter will be applied

Only the first function matching the filter will be returned for each name.

func (*FuncManager) Lookup

func (m *FuncManager) Lookup(typ FuncType, name string) (any, error)

Lookup will search for a registered function of the given type

type FuncType

type FuncType int

FuncType declares the scope, a supplied function is expected to run in. One function can handle multiple FuncTypes (which may be combined by OR'ing them.

func FTCombine

func FTCombine(typ ...FuncType) FuncType

FTCombine creates a new FuncType by combining multiple separate ones

func (FuncType) Add

func (t FuncType) Add(typ FuncType) FuncType

Add will return a FuncType, which has typ active as well

func (FuncType) String

func (t FuncType) String() string

String will return a textual representation of all active types.

func (FuncType) Test

func (t FuncType) Test(typ FuncType) bool

Test will check, wether the FuncType typ is set When multiply types are active in typ, Test will return true when at least one of them is active in t.

type GetContent

type GetContent interface {
	GetFunction(v interface{}) (reflect.Value, error)
}

GetContent is the interface for a ContentItem's getter

type ItemControl

type ItemControl interface {
	// Set the current items' position
	SetPosition(pos Position)
	// Format a string describing the items' Position
	GetPosition() string
	// Retrieve items position
	Position() Position
	// Create an error on the current item
	Errorf(errorFormat string, a ...interface{}) error
	// Check, wether the error has position information and add the
	// items' information, if not.
	PosError(err error) error
	// Is called as Notification for the element, that it has been added to an outer loop
	RegisterLoop(l ItemControl, depth int) error
}

ItemControl is the basic interface for an item

The basic interface for all tokens; needed for position-information (within the template file) and error reporting

Usually, an ItemControl, which provides content, implements either ItemControlSingle, ItemControlMulti or ItemControlValue

func Position2ItemControl

func Position2ItemControl(pos Position) ItemControl

type ItemControlCheckable

type ItemControlCheckable interface {
	ItemControl
	Check() error
}

When an ItemControl provides some checks, which can be performed after parsing a template (the content may not be available), it should implement ItemControlCheckable

type ItemControlList

type ItemControlList struct {
	BasePosItem
	// contains filtered or unexported fields
}

ItemControlList is a generic Container for a list of Items

func CreateListItem

func CreateListItem() *ItemControlList

CreateListItem will return an empty ItemControlList

func (*ItemControlList) Append

func (cl *ItemControlList) Append(n ...ItemControl) *ItemControlList

Append will append one or more Items to the list

func (*ItemControlList) Check

func (cl *ItemControlList) Check() error

Check passes the Check request to all elements in the list and returns the first error (if there is any)

func (*ItemControlList) Content

func (cl *ItemControlList) Content() ([]TmplFunc, error)

Content returns the TmplFunc for all elements in the list

func (*ItemControlList) Create

func (cl *ItemControlList) Create() *ItemControlList

Create will (re-)initilize and drain the current list

func (*ItemControlList) DoStrip

func (cl *ItemControlList) DoStrip(pred bool)

DoStrip will strip only the first/last element of the list

func (*ItemControlList) Length

func (cl *ItemControlList) Length() int

Length returns the number of Items currently embedded in the list.

The number is retrieved recursively from the items in the list

func (*ItemControlList) RegisterLoop

func (cl *ItemControlList) RegisterLoop(l ItemControl, depth int) error

RegisterLoop registers the loop for all items in the list (unmodified)

func (*ItemControlList) Strip

func (cl *ItemControlList) Strip(pred bool) bool

Strip will pass the Stripping-request from the first/last element in the list

type ItemControlMulti

type ItemControlMulti interface {
	ItemControl
	// Content is generating the list of TmplFunc from the inner Items.
	//
	// Content should try to break the references on the ItemControl to help
	// reducing memory.
	//
	// It may be possible, that the returned function will be embedded within
	// a larger list of functions. Therefore these shoul not be considered
	// as a complete block
	Content() ([]TmplFunc, error)
	// Length returns the number of functions returned by Content().
	Length() int
}

ItemControlMulti is an ItemControl, representing multiple content items ( usually a block )

The returned functions may not be all of the same type, the ItemControl even may contain a collection of inner ItemControls.

type ItemControlPrecompiled

type ItemControlPrecompiled struct {
	BasePosItem
	// contains filtered or unexported fields
}

ItemControlPrecompiled is a container for TmplFunc(), which have been provided externally

func CreatePrecompiledItem

func CreatePrecompiledItem(ctnt []TmplFunc) *ItemControlPrecompiled

Create a new ItemControlPrecompiled object using the user-provided functions

func (*ItemControlPrecompiled) Content

func (pre *ItemControlPrecompiled) Content() ([]TmplFunc, error)

Content returns the provided functions

func (*ItemControlPrecompiled) Create

Create (re-)initializes the object

func (*ItemControlPrecompiled) Length

func (pre *ItemControlPrecompiled) Length() int

Length returns the number of functions provided

type ItemControlSingle

type ItemControlSingle interface {
	ItemControl
	// FuncContent creates the function to create the document
	// output based on the userdata.
	//
	// The function returned by FuncContent() should work without
	// references to the ItemControl object, so that the latter can
	// be freed after parsing.
	//
	// In case, none of the generating content depends on any userdata
	// the parsing and content generation may take directly within
	// FuncContent, so that the returned TmplFunc can just write the
	// prerendered values
	FuncContent() (TmplFunc, error)
}

ItemControlSingle is an ItemControl, that represents a single content item.

type ItemControlStripable

type ItemControlStripable interface {
	ItemControl
	// DoStrip is called to actually strip the current element
	// If pred is true, the beginning of the element is stripped,
	// otherwise the end.
	DoStrip(pred bool)
}

ItemControlStripable should be implemented, when the item can remove leading/trailing spaces

type ItemControlStripper

type ItemControlStripper interface {
	ItemControl
	// Strip is called, to evaluate, wether the surrounding element
	// (predecessor of pred is true, successor otherwise) shall be
	// stripped.
	Strip(pred bool) bool
}

ItemControlStripper should be implement, if the element can decide, wether a preceeding or succeeding element should be stripped (trailing/leading spaces should be removed)

type ItemControlValue

type ItemControlValue interface {
	ItemControl
	Value() (TmplValue, error)
}

ItemControlValue is an ItemControl which should be used, when the containing content represents some (render-time variable) content - in contrast to eg. control items.

type ItemScope

type ItemScope struct {
	BasePosItem
	// contains filtered or unexported fields
}

ItemScope manages the scope of (template-bound) variables

when managing variables, their scope is most often important to not overwrite outer values when calling functions or blocks

While the scope itself doesn't have direct impact on the documents' output, it is defined by the structure of the template. Generally spoken, the variable of an inner scope should not be leaked outside that scope, but variables form the outside should be accessible.

To fulfill this task, a new ItemScope can be generated from an existing (outer) scope, by copying all name-Item-relations of that scope. The newly created (inner) scope has now access to all existing variables, while new variables will only be created in the inner scope. When scope is left, it can be discarded cleanly and the outer scope can be used again.

It is important to manage, that only the first level of variables is copied, so the elements within eg. a map of a map will be modified in the outer scope as well (if not copied explicitly)

func CreateRootScope

func CreateRootScope() *ItemScope

CreateRootScope creates a new, empty scope

func CreateScope

func CreateScope(scp *ItemScope) *ItemScope

CreateScope creates a new (inner) scope from the outer scope scp

func (*ItemScope) Create

func (scp *ItemScope) Create() *ItemScope

Create generates a new (inner) scope from the current one.

func (*ItemScope) Declare

func (scp *ItemScope) Declare(name string, val ItemControlValue, declare ItemScopeSet) error

Declare creates a new variable with value val. If it already exists, declare decides, how to handle the situation

func (*ItemScope) Get

func (scp *ItemScope) Get(name string) ItemControlValue

Get looks up an existing variable in the current scope. returns nil if the variable name doesn't exists.

func (*ItemScope) GetDefault

func (scp *ItemScope) GetDefault(name string, def ItemControlValue) ItemControlValue

GetDefault looks up an existing variable, but will return dev, if the variable name doesn't exists.

func (*ItemScope) GetOrCreate

func (scp *ItemScope) GetOrCreate(name string, def ItemControlValue) ItemControlValue

GetOrCreate looks up the existing variable name. If it doesn't exist, a new will be generated and filled by def

func (*ItemScope) Set

func (scp *ItemScope) Set(name string, val ItemControlValue) error

Set creates a new variable with the value val

If the variable already exists, the old value will be overwritten

type ItemScopeSet

type ItemScopeSet int

type IteratorItem

type IteratorItem interface {
	ItemControlValue
	Init() ItemControlValue
	Test() ItemControlValue
	Increment() ItemControlValue
	CountValue() ItemControlValue
	EachValue() (TmplValue, TmplValue, error)
}

A IteratorItem provides functionality for a convenient iterator, eg. for a LoopItem.

The IteratorItem can generate is a ItemControlValue (returning the currently active item) and can generate three other (linked) ItemControlValue:

* Init - usually returning an invalid value and setting up the iterator * Test - testing the iterator and returning true as long as the current item is valid * Increment - Selecting the next element

Furthermore, EachValue() can be used for iterators where more than one value is currently active.

type LoopControlItem

type LoopControlItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

The LoopControlItem provides functionality to handle abort conditions for loops, like `continue` or `break` statements

func CreateBreakItem

func CreateBreakItem() *LoopControlItem

CreateBreak will create a LoopControlItem, which stops the loop completly

func CreateContinueItem

func CreateContinueItem() *LoopControlItem

CreateContinue will create a LoopControlItem which will only stop the current loop iteration and start the next (if valid)

func (*LoopControlItem) Check

func (c *LoopControlItem) Check() error

Check will determine, wether a LoopItem has been registered and error out, if not

func (*LoopControlItem) Create

func (c *LoopControlItem) Create(t loopControl) *LoopControlItem

Create will (Re-)Initialize the current item to the specified type

func (*LoopControlItem) FuncContent

func (c *LoopControlItem) FuncContent() (TmplFunc, error)

func (*LoopControlItem) RegisterLoop

func (c *LoopControlItem) RegisterLoop(l ItemControl, depth int) error

RegisterLoop will set the nearest loop as target for the LoopControl

func (*LoopControlItem) Value

func (c *LoopControlItem) Value() (TmplValue, error)

type LoopItem

type LoopItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

LoopItem controls the complete loop lifecycle.

Upon document generation, when the loop is started, the ItemControlValues for init, test and increment will be executed for each iteration.

For each iteration the items registered in the block will be executed. If the loop doesn't run a single iteration, the optional elseblock will be executed.

func CreateLoopItem

func CreateLoopItem(init, test, increment ItemControl, block ItemControlMulti) *LoopItem

CreateLoopItem will create a LoopItem with explicit init, test and increment Item.

func CreateValueLoopItem

func CreateValueLoopItem(iter IteratorItem, block ItemControlMulti) *LoopItem

CreateValueLoopItem will create a LoopItem based on an IteratorItem

init, test and increment will be provided by iter.

func (*LoopItem) Append

func (l *LoopItem) Append(block ItemControlMulti) *LoopItem

Append will append the given ItemControl to the current block

func (*LoopItem) AppendElse

func (l *LoopItem) AppendElse(block ItemControlMulti) *LoopItem

AppendElse will append the given ItemControl to the current elseblock

func (*LoopItem) Check

func (l *LoopItem) Check() error

Check() will pass the checkable to all elements in the block and in the iterator components

func (*LoopItem) Create

func (l *LoopItem) Create(init, test, increment ItemControl) *LoopItem

Create will (Re-)Initialize the LoopItem with iterator elements and drained blocks

func (*LoopItem) FuncContent

func (l *LoopItem) FuncContent() (TmplFunc, error)

FuncContent will return the TmplFunc, to use for document generation.

func (*LoopItem) RegisterLoop

func (l *LoopItem) RegisterLoop(i ItemControl, depth int) error

RegisterLoop will Register the current loop to all embedded items, the loop-depth will thereby be incremented by one.

type OnErrorHdl

type OnErrorHdl func(err error) (reflect.Value, error)

type Position

type Position interface {
	Line() int
	Column() int
	String() string
}

A Position is just a pointer within a text, described by Line() and Column()

type PositionError

type PositionError interface {
	error
	Position() Position
}

PositionError is an error with position information

type PositionFile

type PositionFile interface {
	PositionName
	Update(msg string)
	Set(l, c int) PositionFile
}

PositionFile can Update the PositionName, when new data is read. The current position should always point to the _beginning_ of the string.

func CreatePosition

func CreatePosition(name string) PositionFile

CreatePosition returns a Position handle for a given Filename

type PositionName

type PositionName interface {
	Position
	Name() string
}

PositionName is a Position with an (additional File-) Name

type RenderContent

type RenderContent interface {
	RenderFunction(w io.Writer, v reflect.Value) error
}

RenderContent is the interface for a ContentItem's renderer

type SelectContent

type SelectContent interface {
	SelectFunction(ud interface{}, v reflect.Value) (reflect.Value, error)
}

SelectContent is the interface for a ContentItem's selector

type SelectOnMissingHdl

type SelectOnMissingHdl func(name string, innerErr error) (reflect.Value, error)

type SequenceIteratorItem

type SequenceIteratorItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

A SequenceIteratorItem is a simple counter used to control many loops

func CreateSequenceDownIteratorItem

func CreateSequenceDownIteratorItem(start int) *SequenceIteratorItem

CreateSequenceDownIteratorItem returns an IteratorItem, which starts at start and counts down until 0 is reached (not including 0)

func CreateSequenceDownStepIteratorItem

func CreateSequenceDownStepIteratorItem(start, step int) *SequenceIteratorItem

CreateSequenceDownStepIteratorItem returns an IteratorItem which starts at start and counts down by step on each iteration

func CreateSequenceIteratorItem

func CreateSequenceIteratorItem(limit int) *SequenceIteratorItem

CreateSequenceIteratorItem returns an IteratorItem, which starts at 0 and increments by one until the limit is reached (not included)

func CreateSequenceRangeIteratorItem

func CreateSequenceRangeIteratorItem(start, step, limit int) *SequenceIteratorItem

CreateSequenceRangeIteratorItem can be used to create an IteratorItem for arbitrary ranges and steps.

For down-stepping step should be negative

func CreateSequenceStepIteratorItem

func CreateSequenceStepIteratorItem(limit, step int) *SequenceIteratorItem

CreateStepIteratorItem returns an IteratorItem, which starts at 0 and increments by step for each iteration until limit is reached

func (*SequenceIteratorItem) CountValue

func (iter *SequenceIteratorItem) CountValue() ItemControlValue

CountValue returns a ItemValue for the current iteration number

func (*SequenceIteratorItem) Create

func (iter *SequenceIteratorItem) Create(start, step, limit int) *SequenceIteratorItem

Create (re-)initializes a SequenceIterartorItem with arbitrary range information

func (*SequenceIteratorItem) EachValue

func (iter *SequenceIteratorItem) EachValue() (TmplValue, TmplValue, error)

EachValue returns the current iterator value and the iteration number (starting at 0 and incrementing by one for each iteration)

func (*SequenceIteratorItem) Increment

func (iter *SequenceIteratorItem) Increment() ItemControlValue

Increment returns the ItemControlValue to increment during document generation

func (*SequenceIteratorItem) Init

Init returns the ItemControlValue used to initialize the iterator

func (*SequenceIteratorItem) Set

func (iter *SequenceIteratorItem) Set(value int) ItemControlValue

Set can be used to set the Iterator to a specific value

The function returns the ItemControlValue to perform this task during rendering

func (*SequenceIteratorItem) Test

Test returns the ItemControlValue to test, wether the limit has already be reached

func (*SequenceIteratorItem) TestAt

func (iter *SequenceIteratorItem) TestAt(limit int, trueAfter bool) ItemControlValue

TestAt returns an ItemControlValue, which can be used to check (during document generation) wether a certain limit already has been reached

If trueAfter is set, the check-logic will be inverted, with resp. to Test So, TestAt(2, false) will return true for 0 and 1 (like Test) and false for anything starting from 2. TestAt(2, true) will return false for 0, 1 and 2, and true for everything greater.

func (*SequenceIteratorItem) Value

func (iter *SequenceIteratorItem) Value() (TmplValue, error)

Value returns the current iterator value

type TextItem

type TextItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

TextItem is a ItemControlStrippable containing (otherwise) static text

func CreateTextItem

func CreateTextItem(txt string) *TextItem

Create a TextItem sending the text specified in txt to the resulting document

func (*TextItem) Content

func (t *TextItem) Content() ([]TmplFunc, error)

func (*TextItem) Create

func (t *TextItem) Create(txt string) *TextItem

Create (re-)initiize the item with the text in txt

func (*TextItem) DoStrip

func (t *TextItem) DoStrip(pred bool)

func (*TextItem) FuncContent

func (t *TextItem) FuncContent() (TmplFunc, error)

func (*TextItem) Length

func (t *TextItem) Length() int

func (*TextItem) Value

func (t *TextItem) Value() (TmplValue, error)

type TmplFunc

type TmplFunc func(w io.Writer, val interface{}) error

TmplFunc represents a compiled item

After compilation, every token is reduced to zero, one or more TmplFunc which are called in order with the choosen output and input values.

When called, w can be used to write to the output document. The parameter val will contain the data passed by the user for document generation.

func GetMultiContent

func GetMultiContent(i ItemControl) ([]TmplFunc, error)

GetMultiContent creates a list of TmplFunc from the given ItemControl

If the item was a ItemControlSingle or ItemControlValue, it is mapped accordingly

func GetSingleContent

func GetSingleContent(i ItemControl, mergeMulti bool) (TmplFunc, error)

GetSingleContent creates a single content (TmplFunc) item from the given ItemControl.

If the content expands to multeple TmplFunc, the mergeMulti argument will decide, wether this is an error or if all of those calls are merged into a single TmplFunc.

func RenderValue

func RenderValue(fn TmplValue) (TmplFunc, error)

RenderValue will wrap a TmplValue within a TmplFunc

type TmplValue

type TmplValue func(val interface{}) (reflect.Value, error)

TmplValue represents the value-generation of a compiled item

Alternatively, items which represent a certain value, which usually isn't known at time of template compilation, a TmplValue can be created. This allows conditional functionality in the template to work on values and not only on rendered text.

returning a nil-value or Zero value is allowed and will result in no output when rendering the template.

func GetValue

func GetValue(i ItemControl) (TmplValue, error)

GetValue gets the value from the current item.

If it doesn't implement ItemControlValue, but ItemControlSingle, the rendered result will be used as value instead.

type ValueIteratorItem

type ValueIteratorItem struct {
	BasePosItem
	// contains filtered or unexported fields
}

ValueIteratorItem can be used for the usual iteration over some complex data, like arrays or maps

func CreateValueIteratorItem

func CreateValueIteratorItem(val ItemControl) *ValueIteratorItem

CreateValueIterator returns an IteratorItem for going over complex data

func (*ValueIteratorItem) CountValue

func (v *ValueIteratorItem) CountValue() ItemControlValue

func (*ValueIteratorItem) Create

Create (re-)initializes the given IteratorItem

func (*ValueIteratorItem) EachValue

func (v *ValueIteratorItem) EachValue() (TmplValue, TmplValue, error)

func (*ValueIteratorItem) Increment

func (v *ValueIteratorItem) Increment() ItemControlValue

func (*ValueIteratorItem) Init

func (*ValueIteratorItem) Test

func (*ValueIteratorItem) Value

func (v *ValueIteratorItem) Value() (TmplValue, error)

Jump to

Keyboard shortcuts

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