messageformat

package module
v0.0.0-...-c3f8592 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2021 License: MIT Imports: 13 Imported by: 2

README

What is this?

This is a Go implementation of ICU MessageFormat.

How to build

This library depends on icu4c 67.1

On macOS, the simplest way is to install it with brew

brew install icu4c

Since macOS comes with its own icu4c, in order for the Go toolchain to find our installation of icu4c, we have to set the following environment variable.

export PKG_CONFIG_PATH="/usr/local/opt/icu4c/lib/pkgconfig"

Example

package main

import (
	"fmt"

	"github.com/iawaknahc/gomessageformat"
	"golang.org/x/text/language"
)

func main() {
	// Try change numFiles to 0 or 2.
	numFiles := 1
	out, err := messageformat.FormatPositional(
		language.English,
		`{0, plural,
			=0 {There are no files on disk.}
			=1 {There is only 1 file on disk.}
			other {There are # files on disk.}
		}`,
		numFiles,
	)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", out)
}

Caveats

  • The only implemented ApostropheMode is DOUBLE_REQUIRED
  • Supported numeric types are [u]int[8|16|32|64]. Additionally, string is supported as long as it is in integral[.fraction] format.
  • Plural offset must be non-negative integer.
  • The supported arguments are
    • {arg}
    • {arg, select}
    • {arg, plural}
    • {arg, selectordinal}
    • {arg, date, long | medium | long | full}
    • {arg, time, long | medium | long | full}
    • {arg, datetime, long | medium | long | full}

Documentation

Index

Examples

Constants

View Source
const TemplateRuntimeFuncName = "__messageformat__"

TemplateRuntimeFuncName is the name of the runtime helper function used in the output template.

Variables

View Source
var ErrLeadingZeroNumber = errors.New("number must not have leading zero")
View Source
var ErrUnterminatedQuotedString = errors.New("unterminated quoted string")

Functions

func Cardinal

func Cardinal(lang language.Tag, number interface{}) (out string, err error)

Cardinal determines the cardinal form of number in lang.

func FormatNamed

func FormatNamed(tag language.Tag, pattern string, args map[string]interface{}) (out string, err error)

FormatNamed parses pattern and format to string with a map of args.

func FormatPositional

func FormatPositional(tag language.Tag, pattern string, args ...interface{}) (out string, err error)

FormatPositional parses pattern and format to string with a slice of args.

Example
numFiles := 1
out, err := FormatPositional(
	language.English,
	`{0, plural,
			=0 {There are no files on disk.}
			=1 {There is only 1 file on disk.}
			other {There are # files on disk.}
		}`,
	numFiles,
)
if err != nil {
	panic(err)
}
fmt.Printf("%s\n", out)
Output:

There is only 1 file on disk.

func FormatTemplateParseTree

func FormatTemplateParseTree(tag language.Tag, pattern string) (tree *templateparse.Tree, err error)

FormatTemplateParseTree turns pattern into a text/template/parse.Tree. This is the recommended way to use messageformat with html/template where you can include HTML in your translation.

Example
tree, err := FormatTemplateParseTree(language.English,
	`Hello there! Check <a href="{LINK}">this</a> out!`)
if err != nil {
	panic(err)
}

template := htmltemplate.New("main")
template.Funcs(htmltemplate.FuncMap{
	TemplateRuntimeFuncName: TemplateRuntimeFunc,
	"makemap": func(pairs ...interface{}) map[string]interface{} {
		out := make(map[string]interface{})
		for i := 0; i < len(pairs); i += 2 {
			key := pairs[i].(string)
			value := pairs[i+1]
			out[key] = value
		}
		return out
	},
})

_, err = template.Parse(`<!DOCTYPE html><html><head><title>Hi</title></head><body><p>{{ template "greeting" (makemap "LINK" .Link) }}</p></body></html>`)
if err != nil {
	panic(err)
}

_, err = template.AddParseTree("greeting", tree)
if err != nil {
	panic(err)
}
var buf strings.Builder
err = template.Execute(&buf, map[string]interface{}{
	"Link": "https://www.example.com",
})
if err != nil {
	panic(err)
}
fmt.Printf("%s\n", buf.String())
Output:

<!DOCTYPE html><html><head><title>Hi</title></head><body><p>Hello there! Check <a href="https://www.example.com">this</a> out!</p></body></html>

func IVWFT

func IVWFT(number interface{}) (i, v, w, f, t int, err error)

IVWFT derives i, v, w, f, t from number according to https://unicode.org/reports/tr35/tr35-numbers.html#Operands

func IsEmptyParseTree

func IsEmptyParseTree(tree *templateparse.Tree) bool

func Ordinal

func Ordinal(lang language.Tag, number interface{}) (out string, err error)

Ordinal determines the ordinal form of number in lang.

func TemplateRuntimeFunc

func TemplateRuntimeFunc(typ string, args ...interface{}) interface{}

TemplateRuntimeFunc is the runtime helper function used in the output template.

Types

type Argument

type Argument struct {
	Name  string
	Index int
}

Argument is either named argument or positional argument.

type DateArgNode

type DateArgNode struct {
	Arg   Argument
	Style string
}

DateArgNode is `{Argument, date, short | medium | long | full}`.

type DatetimeArgNode

type DatetimeArgNode struct {
	Arg   Argument
	Style string
}

DatetimeArgNode is `{Argument, datetime, short | medium | long | full}`.

type Node

type Node interface {
	// contains filtered or unexported methods
}

Node is an semantic item.

func Parse

func Parse(s string) ([]Node, error)

Parse parses the pattern s into message.

type NoneArgNode

type NoneArgNode struct {
	Arg Argument
}

NoneArgNode is `{Argument}`.

type PluralArgNode

type PluralArgNode struct {
	Arg Argument
	// plural or selectordinal
	Kind    string
	Offset  int
	Clauses []PluralClause
}

PluralArgNode is `{Argument, plural | selectordinal, [offset:number] PluralClause+}`.

type PluralClause

type PluralClause struct {
	// If Keyword is empty, use ExplicitValue
	Keyword       string
	ExplicitValue int
	Nodes         []Node
}

PluralClause is `(keyword | =ExplicitValue) {message}`.

type PoundNode

type PoundNode struct{}

PoundNode is `#`.

type SelectArgNode

type SelectArgNode struct {
	Arg     Argument
	Clauses []SelectClause
}

SelectArgNode is `{Argument, select, SelectClause+}`.

type SelectClause

type SelectClause struct {
	Keyword string
	Nodes   []Node
}

SelectClause is `Keyword {message}`.

type TextNode

type TextNode struct {
	Value string
}

TextNode is a text segment.

type TimeArgNode

type TimeArgNode struct {
	Arg   Argument
	Style string
}

TimeArgNode is `{Argument, time, short | medium | long | full}`.

type Token

type Token struct {
	Type  TokenType
	Value string
}

func (Token) String

func (t Token) String() string

type TokenType

type TokenType int
const (
	TokenTypeEOF TokenType = iota
	TokenTypeText
	TokenTypeWord
	TokenTypeNumber
	TokenTypeLBrace
	TokenTypeRBrace
	TokenTypeComma
	TokenTypeEqual
	TokenTypePound
	TokenTypeColon
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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