Package message
Package message implements formatted I/O for localized strings with functions
analogous to the fmt's print functions. It is a drop-in replacement for fmt.
A format string can be localized by replacing any of the print functions of
fmt with an equivalent call to a Printer.
p := message.NewPrinter(message.MatchLanguage("en"))
p.Println(123456.78) // Prints 123,456.78
p.Printf("%d ducks in a row", 4331) // Prints 4,331 ducks in a row
p := message.NewPrinter(message.MatchLanguage("nl"))
p.Printf("Hoogte: %.1f meter", 1244.9) // Prints Hoogte: 1,244.9 meter
p := message.NewPrinter(message.MatchLanguage("bn"))
p.Println(123456.78) // Prints ১,২৩,৪৫৬.৭৮
Printer currently supports numbers and specialized types for which packages
exist in x/text. Other builtin types such as time.Time and slices are
planned.
Format strings largely have the same meaning as with fmt with the following
notable exceptions:
- flag # always resorts to fmt for printing
- verb 'f', 'e', 'g', 'd' use localized formatting unless the '#' flag is
specified.
- verb 'm' inserts a translation of a string argument.
See package fmt for more options.
Translation
The format strings that are passed to Printf, Sprintf, Fprintf, or Errorf
are used as keys to look up translations for the specified languages.
More on how these need to be specified below.
One can use arbitrary keys to distinguish between otherwise ambiguous
strings:
p := message.NewPrinter(language.English)
p.Printf("archive(noun)") // Prints "archive"
p.Printf("archive(verb)") // Prints "archive"
p := message.NewPrinter(language.German)
p.Printf("archive(noun)") // Prints "Archiv"
p.Printf("archive(verb)") // Prints "archivieren"
To retain the fallback functionality, use Key:
p.Printf(message.Key("archive(noun)", "archive"))
p.Printf(message.Key("archive(verb)", "archive"))
Translation Pipeline
Format strings that contain text need to be translated to support different
locales. The first step is to extract strings that need to be translated.
1. Install gotext
go get -u golang.org/x/text/cmd/gotext
gotext -help
2. Mark strings in your source to be translated by using message.Printer,
instead of the functions of the fmt package.
3. Extract the strings from your source
gotext extract
The output will be written to the textdata directory.
4. Send the files for translation
It is planned to support multiple formats, but for now one will have to
rewrite the JSON output to the desired format.
5. Inject translations into program
6. Repeat from 2
Right now this has to be done programmatically with calls to Set or
SetString. These functions as well as the methods defined in
see also package golang.org/x/text/message/catalog can be used to implement
either dynamic or static loading of messages.
Translated messages can vary based on the plural and gender forms of
substitution values. In general, it is up to the translators to provide
alternative translations for such forms. See the packages in
golang.org/x/text/feature and golang.org/x/text/message/catalog for more
information.
▾ Example (Http)
Code:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
lang, _ := r.Cookie("lang")
accept := r.Header.Get("Accept-Language")
fallback := "en"
tag := message.MatchLanguage(lang.String(), accept, fallback)
p := message.NewPrinter(tag)
p.Fprintln(w, "User language is", tag)
})
- Variables
- func MatchLanguage(preferred ...string) language.Tag
- func Set(tag language.Tag, key string, msg ...catalog.Message) error
- func SetString(tag language.Tag, key string, msg string) error
- type Option
- func Catalog(c catalog.Catalog) Option
- type Printer
- func NewPrinter(t language.Tag, opts ...Option) *Printer
- func (p *Printer) Fprint(w io.Writer, a ...interface{}) (n int, err error)
- func (p *Printer) Fprintf(w io.Writer, key Reference, a ...interface{}) (n int, err error)
- func (p *Printer) Fprintln(w io.Writer, a ...interface{}) (n int, err error)
- func (p *Printer) Print(a ...interface{}) (n int, err error)
- func (p *Printer) Printf(key Reference, a ...interface{}) (n int, err error)
- func (p *Printer) Println(a ...interface{}) (n int, err error)
- func (p *Printer) Sprint(a ...interface{}) string
- func (p *Printer) Sprintf(key Reference, a ...interface{}) string
- func (p *Printer) Sprintln(a ...interface{}) string
- type Reference
- func Key(id string, fallback string) Reference
Package files
catalog.go
doc.go
format.go
message.go
print.go
Variables
DefaultCatalog is used by SetString.
var DefaultCatalog catalog.Catalog = defaultCatalog
func MatchLanguage(preferred ...string) language.Tag
MatchLanguage reports the matched tag obtained from language.MatchStrings for
the Matcher of the DefaultCatalog.
func Set(tag language.Tag, key string, msg ...catalog.Message) error
Set calls Set on the initial default Catalog.
func SetString(tag language.Tag, key string, msg string) error
SetString calls SetString on the initial default Catalog.
An Option defines an option of a Printer.
type Option func(o *options)
func Catalog(c catalog.Catalog) Option
Catalog defines the catalog to be used.
A Printer implements language-specific formatted I/O analogous to the fmt
package.
type Printer struct {
}
▾ Example (MVerb)
Code:
message.SetString(language.Dutch, "You have chosen to play %m.", "U heeft ervoor gekozen om %m te spelen.")
message.SetString(language.Dutch, "basketball", "basketbal")
message.SetString(language.Dutch, "hockey", "ijshockey")
message.SetString(language.Dutch, "soccer", "voetbal")
message.SetString(language.BritishEnglish, "soccer", "football")
for _, sport := range []string{"soccer", "basketball", "hockey"} {
for _, lang := range []string{"en", "en-GB", "nl"} {
p := message.NewPrinter(language.Make(lang))
fmt.Printf("%-6s %s\n", lang, p.Sprintf("You have chosen to play %m.", sport))
}
fmt.Println()
}
Output:
en You have chosen to play soccer.
en-GB You have chosen to play football.
nl U heeft ervoor gekozen om voetbal te spelen.
en You have chosen to play basketball.
en-GB You have chosen to play basketball.
nl U heeft ervoor gekozen om basketbal te spelen.
en You have chosen to play hockey.
en-GB You have chosen to play hockey.
nl U heeft ervoor gekozen om ijshockey te spelen.
▾ Example (Numbers)
Code:
for _, lang := range []string{"en", "de", "de-CH", "fr", "bn"} {
p := message.NewPrinter(language.Make(lang))
p.Printf("%-6s %g\n", lang, 123456.78)
}
Output:
en 123,456.78
de 123.456,78
de-CH 123’456.78
fr 123 456,78
bn ১,২৩,৪৫৬.৭৮
func NewPrinter(t language.Tag, opts ...Option) *Printer
NewPrinter returns a Printer that formats messages tailored to language t.
func (*Printer) Fprint
¶
func (p *Printer) Fprint(w io.Writer, a ...interface{}) (n int, err error)
Fprint is like fmt.Fprint, but using language-specific formatting.
func (*Printer) Fprintf
¶
func (p *Printer) Fprintf(w io.Writer, key Reference, a ...interface{}) (n int, err error)
Fprintf is like fmt.Fprintf, but using language-specific formatting.
func (p *Printer) Fprintln(w io.Writer, a ...interface{}) (n int, err error)
Fprintln is like fmt.Fprintln, but using language-specific formatting.
func (*Printer) Print
¶
func (p *Printer) Print(a ...interface{}) (n int, err error)
Print is like fmt.Print, but using language-specific formatting.
func (*Printer) Printf
¶
func (p *Printer) Printf(key Reference, a ...interface{}) (n int, err error)
Printf is like fmt.Printf, but using language-specific formatting.
func (*Printer) Println
¶
func (p *Printer) Println(a ...interface{}) (n int, err error)
Println is like fmt.Println, but using language-specific formatting.
func (*Printer) Sprint
¶
func (p *Printer) Sprint(a ...interface{}) string
Sprint is like fmt.Sprint, but using language-specific formatting.
func (*Printer) Sprintf
¶
func (p *Printer) Sprintf(key Reference, a ...interface{}) string
Sprintf is like fmt.Sprintf, but using language-specific formatting.
func (p *Printer) Sprintln(a ...interface{}) string
Sprintln is like fmt.Sprintln, but using language-specific formatting.
A Reference is a string or a message reference.
type Reference interface {
}
func Key(id string, fallback string) Reference
Key creates a message Reference for a message where the given id is used for
message lookup and the fallback is returned when no matches are found.
Subdirectories
Name |
Synopsis |
.. |
catalog
|
Package catalog defines collections of translated format strings.
|
pipeline
|
Package pipeline provides tools for creating translation pipelines.
|