template

package
v0.0.0-...-43e9c62 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrDuplicateDeclaration      = errors.New("duplicate declaration")
	ErrDuplicateOptionName       = errors.New("duplicate option name")
	ErrFormatting                = errors.New("formatting error")
	ErrMissingSelectorAnnotation = errors.New("missing selector annotation")
	// ErrOperandMismatch is an Invalid Expression error that occurs when an operand provided
	// to a function during function resolution does not match one of the expected
	// implementation-defined types for that function; or in which a literal operand value does not
	// have the required format and thus cannot be processed into one of the expected
	// implementation-defined types for that specific function.
	ErrOperandMismatch       = errors.New("operand mismatch")
	ErrSelection             = errors.New("selection error")
	ErrSyntax                = errors.New("syntax error")
	ErrUnknownFunction       = errors.New("unknown function reference")
	ErrUnresolvedVariable    = errors.New("unresolved variable")
	ErrUnsupportedExpression = errors.New("unsupported expression")
	ErrUnsupportedStatement  = errors.New("unsupported statement")
)

MessageFormat2 Errors as defined in the specification.

https://github.com/unicode-org/message-format-wg/blob/1dc84e648a6f98d74ac62306abaacc0bed8e4fc5/spec/errors.md

Functions

This section is empty.

Types

type Func

type Func func(operand any, options map[string]any) (string, error)

Func is a function, that will be called when a function is encountered in the template.

type Option

type Option func(t *Template)

Option is a template option.

func WithFunc

func WithFunc(name string, f RegistryFunc) Option

WithFunc adds a single function to function registry.

func WithFuncs

func WithFuncs(reg Registry) Option

WithFuncs adds functions to function registry.

func WithLocale

func WithLocale(locale language.Tag) Option

type Options

type Options map[string]any

Options are a possible options for the function.

func (Options) GetInt

func (o Options) GetInt(name string, fallback int, validate ...Validate[int]) (int, error)

GetInt returns the value by name. If the value is not found, returns the fallback value. If the value is not in allowed list, return error.

func (Options) GetString

func (o Options) GetString(name, fallback string, validate ...Validate[string]) (string, error)

GetString returns the value by name. If the value is not found, returns the fallback value. If the value is not in allowed list, return error.

type Registry

type Registry map[string]RegistryFunc

func NewRegistry

func NewRegistry() Registry

NewRegistry returns a new registry with default functions.

type RegistryFunc

type RegistryFunc struct {
	Match  func(input any, options Options, locale language.Tag) (output any, err error)
	Format func(input any, options Options, locale language.Tag) (output any, err error)
}

type SortableVariant

type SortableVariant struct {
	Variant ast.Variant
	Score   int
}

type SortableVariants

type SortableVariants []SortableVariant

func (SortableVariants) Len

func (s SortableVariants) Len() int

func (SortableVariants) Less

func (s SortableVariants) Less(i, j int) bool

func (SortableVariants) Swap

func (s SortableVariants) Swap(i, j int)

type Template

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

Template represents a MessageFormat2 template.

Example (ComplexMessage)
package main

import (
	"fmt"
	"os"

	"go.expect.digital/mf2/template"
	"golang.org/x/text/language"
)

func main() {
	// Define a MF2 string.
	const input = `.local $age = { 42 }
.input { $color :color style=RGB}
{{John is { $age } years old and his favorite color is { $color }.}}`

	color := func(value any, options template.Options, locale language.Tag) (any, error) {
		if value == nil {
			return "", fmt.Errorf("input is required: %w", template.ErrOperandMismatch)
		}

		color, ok := value.(string)
		if !ok {
			return nil, fmt.Errorf("input is not a string: %w", template.ErrOperandMismatch)
		}

		if options == nil {
			return color, nil
		}

		style, err := options.GetString("style", "RGB")
		if err != nil {
			return nil, fmt.Errorf("get style: %w", err)
		}

		var result string

		switch style {
		case "RGB":
			switch color {
			case "red":
				result = "255,0,0"
			case "green":
				result = "0,255,0"
			case "blue":
				result = "0,0,255"
			}
		case "HEX": // Other Implementations
		case "HSL": // Other Implementations
		}

		return result, nil
	}
	// }

	// Parse template.
	t, err := template.New(template.WithFunc("color", template.RegistryFunc{Format: color})).Parse(input)
	if err != nil {
		panic(err)
	}

	// Execute the template.
	if err = t.Execute(os.Stdout, map[string]any{"color": "red"}); err != nil {
		panic(err)
	}

}
Output:

John is 42 years old and his favorite color is 255,0,0.
Example (PlainText)
package main

import (
	"os"

	"go.expect.digital/mf2/template"
)

func main() {
	// Define a MF2 string.
	const input = "Hello World!"

	// Parse template.
	t, err := template.New().Parse(input)
	if err != nil {
		panic(err)
	}

	if err := t.Execute(os.Stdout, nil); err != nil {
		panic(err)
	}

}
Output:

Hello World!
Example (SimpleMessage)
package main

import (
	"os"

	"go.expect.digital/mf2/template"
)

func main() {
	// Define a MF2 string.
	const input = "Today is { $degrees :number signDisplay=always } degrees outside."

	// Parse template.
	t, err := template.New().Parse(input)
	if err != nil {
		panic(err)
	}

	// Execute the template.
	if err = t.Execute(os.Stdout, map[string]any{"degrees": 15}); err != nil {
		panic(err)
	}

}
Output:

Today is +15 degrees outside.

func New

func New(options ...Option) *Template

New returns a new Template.

func (*Template) Execute

func (t *Template) Execute(w io.Writer, input map[string]any) error

Execute writes the result of the template to the given writer.

func (*Template) Parse

func (t *Template) Parse(input string) (*Template, error)

Parse parses the MessageFormat2 string and returns the template.

func (*Template) Sprint

func (t *Template) Sprint(input map[string]any) (string, error)

Sprint wraps Execute and returns the result as a string.

type Validate

type Validate[T any] func(T) error

Jump to

Keyboard shortcuts

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