i18n

package
v2.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2024 License: MIT Imports: 11 Imported by: 874

Documentation

Overview

Package i18n provides support for looking up messages according to a set of locale preferences.

Create a Bundle to use for the lifetime of your application.

bundle := i18n.NewBundle(language.English)

Load translations into your bundle during initialization.

bundle.LoadMessageFile("en-US.yaml")

Create a Localizer to use for a set of language preferences.

func(w http.ResponseWriter, r *http.Request) {
    lang := r.FormValue("lang")
    accept := r.Header.Get("Accept-Language")
    localizer := i18n.NewLocalizer(bundle, lang, accept)
}

Use the Localizer to lookup messages.

    localizer.MustLocalize(&i18n.LocalizeConfig{
	        DefaultMessage: &i18n.Message{
	            ID: "HelloWorld",
	            Other: "Hello World!",
	        },
    })

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bundle

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

Bundle stores a set of messages and pluralization rules. Most applications only need a single bundle that is initialized early in the application's lifecycle. It is not goroutine safe to modify the bundle while Localizers are reading from it.

func NewBundle

func NewBundle(defaultLanguage language.Tag) *Bundle

NewBundle returns a bundle with a default language and a default set of plural rules.

func (*Bundle) AddMessages

func (b *Bundle) AddMessages(tag language.Tag, messages ...*Message) error

AddMessages adds messages for a language. It is useful if your messages are in a format not supported by ParseMessageFileBytes.

func (*Bundle) LanguageTags

func (b *Bundle) LanguageTags() []language.Tag

LanguageTags returns the list of language tags of all the translations loaded into the bundle

func (*Bundle) LoadMessageFile

func (b *Bundle) LoadMessageFile(path string) (*MessageFile, error)

LoadMessageFile loads the bytes from path and then calls ParseMessageFileBytes.

func (*Bundle) LoadMessageFileFS added in v2.2.0

func (b *Bundle) LoadMessageFileFS(fsys fs.FS, path string) (*MessageFile, error)

LoadMessageFileFS is like LoadMessageFile but instead of reading from the hosts operating system's file system it reads from the fs file system.

func (*Bundle) MustAddMessages

func (b *Bundle) MustAddMessages(tag language.Tag, messages ...*Message)

MustAddMessages is similar to AddMessages except it panics if an error happens.

func (*Bundle) MustLoadMessageFile

func (b *Bundle) MustLoadMessageFile(path string)

MustLoadMessageFile is similar to LoadMessageFile except it panics if an error happens.

func (*Bundle) MustParseMessageFileBytes

func (b *Bundle) MustParseMessageFileBytes(buf []byte, path string)

MustParseMessageFileBytes is similar to ParseMessageFileBytes except it panics if an error happens.

func (*Bundle) ParseMessageFileBytes

func (b *Bundle) ParseMessageFileBytes(buf []byte, path string) (*MessageFile, error)

ParseMessageFileBytes parses the bytes in buf to add translations to the bundle.

The format of the file is everything after the last ".".

The language tag of the file is everything after the second to last "." or after the last path separator, but before the format.

func (*Bundle) RegisterUnmarshalFunc

func (b *Bundle) RegisterUnmarshalFunc(format string, unmarshalFunc UnmarshalFunc)

RegisterUnmarshalFunc registers an UnmarshalFunc for format.

type LocalizeConfig

type LocalizeConfig struct {
	// MessageID is the id of the message to lookup.
	// This field is ignored if DefaultMessage is set.
	MessageID string

	// TemplateData is the data passed when executing the message's template.
	// If TemplateData is nil and PluralCount is not nil, then the message template
	// will be executed with data that contains the plural count.
	TemplateData interface{}

	// PluralCount determines which plural form of the message is used.
	PluralCount interface{}

	// DefaultMessage is used if the message is not found in any message files.
	DefaultMessage *Message

	// Funcs is used to configure a template.TextParser if TemplateParser is not set.
	Funcs texttemplate.FuncMap

	// The TemplateParser to use for parsing templates.
	// If one is not set, a template.TextParser is used (configured with Funcs if it is set).
	TemplateParser template.Parser
}

LocalizeConfig configures a call to the Localize method on Localizer.

type Localizer

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

Localizer provides Localize and MustLocalize methods that return localized messages. Localize and MustLocalize methods use a language.Tag matching algorithm based on the best possible value. This algorithm may cause an unexpected language.Tag returned value depending on the order of the tags stored in memory. For example, if the bundle used to create a Localizer instance ingested locales following this order ["en-US", "en-GB", "en-IE", "en"] and the locale "en" is asked, the underlying matching algorithm will return "en-US" thinking it is the best match possible. More information about the algorithm in this Github issue: https://github.com/golang/go/issues/49176. There is additionnal informations inside the Go code base: https://github.com/golang/text/blob/master/language/match.go#L142

func NewLocalizer

func NewLocalizer(bundle *Bundle, langs ...string) *Localizer

NewLocalizer returns a new Localizer that looks up messages in the bundle according to the language preferences in langs. It can parse Accept-Language headers as defined in http://www.ietf.org/rfc/rfc2616.txt.

func (*Localizer) Localize

func (l *Localizer) Localize(lc *LocalizeConfig) (string, error)

Localize returns a localized message.

func (*Localizer) LocalizeMessage

func (l *Localizer) LocalizeMessage(msg *Message) (string, error)

Localize returns a localized message.

func (*Localizer) LocalizeWithTag

func (l *Localizer) LocalizeWithTag(lc *LocalizeConfig) (string, language.Tag, error)

LocalizeWithTag returns a localized message and the language tag. It may return a best effort localized message even if an error happens.

func (*Localizer) MustLocalize

func (l *Localizer) MustLocalize(lc *LocalizeConfig) string

MustLocalize is similar to Localize, except it panics if an error happens.

Example
package main

import (
	"fmt"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := i18n.NewBundle(language.English)
	localizer := i18n.NewLocalizer(bundle, "en")
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: &i18n.Message{
			ID:    "HelloWorld",
			Other: "Hello World!",
		},
	}))
}
Output:

Hello World!
Example (CustomTemplateDelims)
package main

import (
	"fmt"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := i18n.NewBundle(language.English)
	localizer := i18n.NewLocalizer(bundle, "en")
	helloPersonMessage := &i18n.Message{
		ID:         "HelloPerson",
		Other:      "Hello <<.Name>>!",
		LeftDelim:  "<<",
		RightDelim: ">>",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: helloPersonMessage,
		TemplateData:   map[string]string{"Name": "Nick"},
	}))
}
Output:

Hello Nick!
Example (NoDefaultMessage)
package main

import (
	"fmt"

	"github.com/BurntSushi/toml"
	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := i18n.NewBundle(language.English)
	bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
	bundle.MustParseMessageFileBytes([]byte(`
HelloWorld = "Hello World!"
`), "en.toml")
	bundle.MustParseMessageFileBytes([]byte(`
HelloWorld = "Hola Mundo!"
`), "es.toml")

	{
		localizer := i18n.NewLocalizer(bundle, "en-US")
		fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "HelloWorld"}))
	}
	{
		localizer := i18n.NewLocalizer(bundle, "es-ES")
		fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "HelloWorld"}))
	}
}
Output:

Hello World!
Hola Mundo!
Example (Plural)
package main

import (
	"fmt"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := i18n.NewBundle(language.English)
	localizer := i18n.NewLocalizer(bundle, "en")
	catsMessage := &i18n.Message{
		ID:    "Cats",
		One:   "I have {{.PluralCount}} cat.",
		Other: "I have {{.PluralCount}} cats.",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: catsMessage,
		PluralCount:    1,
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: catsMessage,
		PluralCount:    2,
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: catsMessage,
		PluralCount:    "2.5",
	}))
}
Output:

I have 1 cat.
I have 2 cats.
I have 2.5 cats.
Example (Plural_template)
package main

import (
	"fmt"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := i18n.NewBundle(language.English)
	localizer := i18n.NewLocalizer(bundle, "en")
	personCatsMessage := &i18n.Message{
		ID:    "PersonCats",
		One:   "{{.Name}} has {{.Count}} cat.",
		Other: "{{.Name}} has {{.Count}} cats.",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: personCatsMessage,
		PluralCount:    1,
		TemplateData: map[string]interface{}{
			"Name":  "Nick",
			"Count": 1,
		},
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: personCatsMessage,
		PluralCount:    2,
		TemplateData: map[string]interface{}{
			"Name":  "Nick",
			"Count": 2,
		},
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: personCatsMessage,
		PluralCount:    "2.5",
		TemplateData: map[string]interface{}{
			"Name":  "Nick",
			"Count": "2.5",
		},
	}))
}
Output:

Nick has 1 cat.
Nick has 2 cats.
Nick has 2.5 cats.
Example (Template)
package main

import (
	"fmt"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := i18n.NewBundle(language.English)
	localizer := i18n.NewLocalizer(bundle, "en")
	helloPersonMessage := &i18n.Message{
		ID:    "HelloPerson",
		Other: "Hello {{.Name}}!",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: helloPersonMessage,
		TemplateData:   map[string]string{"Name": "Nick"},
	}))
}
Output:

Hello Nick!

type Message

type Message struct {
	// ID uniquely identifies the message.
	ID string

	// Hash uniquely identifies the content of the message
	// that this message was translated from.
	Hash string

	// Description describes the message to give additional
	// context to translators that may be relevant for translation.
	Description string

	// LeftDelim is the left Go template delimiter.
	LeftDelim string

	// RightDelim is the right Go template delimiter.
	RightDelim string

	// Zero is the content of the message for the CLDR plural form "zero".
	Zero string

	// One is the content of the message for the CLDR plural form "one".
	One string

	// Two is the content of the message for the CLDR plural form "two".
	Two string

	// Few is the content of the message for the CLDR plural form "few".
	Few string

	// Many is the content of the message for the CLDR plural form "many".
	Many string

	// Other is the content of the message for the CLDR plural form "other".
	Other string
}

Message is a string that can be localized.

func MustNewMessage

func MustNewMessage(data interface{}) *Message

MustNewMessage is similar to NewMessage except it panics if an error happens.

func NewMessage

func NewMessage(data interface{}) (*Message, error)

NewMessage parses data and returns a new message.

type MessageFile

type MessageFile struct {
	Path     string
	Tag      language.Tag
	Format   string
	Messages []*Message
}

MessageFile represents a parsed message file.

func ParseMessageFileBytes

func ParseMessageFileBytes(buf []byte, path string, unmarshalFuncs map[string]UnmarshalFunc) (*MessageFile, error)

ParseMessageFileBytes returns the messages parsed from file.

type MessageNotFoundErr

type MessageNotFoundErr struct {
	Tag       language.Tag
	MessageID string
}

MessageNotFoundErr is returned from Localize when a message could not be found.

func (*MessageNotFoundErr) Error

func (e *MessageNotFoundErr) Error() string

type MessageTemplate

type MessageTemplate struct {
	*Message
	PluralTemplates map[plural.Form]*internal.Template
}

MessageTemplate is an executable template for a message.

func NewMessageTemplate

func NewMessageTemplate(m *Message) *MessageTemplate

NewMessageTemplate returns a new message template.

func (*MessageTemplate) Execute

func (mt *MessageTemplate) Execute(pluralForm plural.Form, data interface{}, funcs texttemplate.FuncMap) (string, error)

Execute executes the template for the plural form and template data. Deprecated: This message is no longer used internally by go-i18n and it probably should not have been exported to begin with. Its replacement is not exported. If you depend on this method for some reason and/or have a use case for exporting execute, please file an issue.

type UnmarshalFunc

type UnmarshalFunc func(data []byte, v interface{}) error

UnmarshalFunc unmarshals data into v.

Directories

Path Synopsis
Package template defines a generic interface for template parsers and implementations of that interface.
Package template defines a generic interface for template parsers and implementations of that interface.

Jump to

Keyboard shortcuts

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