go-i18n: github.com/nicksnyder/go-i18n/v2/i18n Index | Examples | Files

package i18n

import "github.com/nicksnyder/go-i18n/v2/i18n"

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

Package Files

bundle.go doc.go localizer.go message.go message_template.go parse.go

type Bundle Uses

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 Uses

func NewBundle(defaultLanguage language.Tag) *Bundle

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

func (*Bundle) AddMessages Uses

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 Uses

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

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

func (*Bundle) LoadMessageFile Uses

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

LoadMessageFile loads the bytes from path and then calls ParseMessageFileBytes.

func (*Bundle) MustAddMessages Uses

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

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

func (*Bundle) MustLoadMessageFile Uses

func (b *Bundle) MustLoadMessageFile(path string)

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

func (*Bundle) MustParseMessageFileBytes Uses

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

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

func (*Bundle) ParseMessageFileBytes Uses

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 Uses

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

RegisterUnmarshalFunc registers an UnmarshalFunc for format.

type LocalizeConfig Uses

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 extend the Go template engine's built in functions
    Funcs template.FuncMap
}

LocalizeConfig configures a call to the Localize method on Localizer.

type Localizer Uses

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

Localizer provides Localize and MustLocalize methods that return localized messages.

func NewLocalizer Uses

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 Uses

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

Localize returns a localized message.

func (*Localizer) LocalizeMessage Uses

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

Localize returns a localized message.

func (*Localizer) LocalizeWithTag Uses

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 Uses

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

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

Code:

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!

Code:

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!

Code:

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!

Code:

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.

Code:

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 Uses

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 Uses

func MustNewMessage(data interface{}) *Message

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

func NewMessage Uses

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

NewMessage parses data and returns a new message.

type MessageFile Uses

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

MessageFile represents a parsed message file.

func ParseMessageFileBytes Uses

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

ParseMessageFileBytes returns the messages parsed from file.

type MessageNotFoundErr Uses

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

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

func (*MessageNotFoundErr) Error Uses

func (e *MessageNotFoundErr) Error() string

type MessageTemplate Uses

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

MessageTemplate is an executable template for a message.

func NewMessageTemplate Uses

func NewMessageTemplate(m *Message) *MessageTemplate

NewMessageTemplate returns a new message template.

func (*MessageTemplate) Execute Uses

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

Execute executes the template for the plural form and template data.

type UnmarshalFunc Uses

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

UnmarshalFunc unmarshals data into v.

Package i18n imports 10 packages (graph) and is imported by 43 packages. Updated 2019-11-24. Refresh now. Tools for package owners.