Files
gotext/translation.go
Ben Sarah Golightly 75a1fb9b04 Add variants of Get functions with existence checks
Currently, a translation that doesn't exist just defaults to the
passed message ID.

It can be helpful to be able to catch these missing cases e.g. to
save to a log.

This PR implements variants ending in 'E' like GetE, GetNE.

This wasn't implemented at the package-level scope, because for
quick translations like that the extra flexibility probably isn't
needed.
2020-07-23 00:28:56 +01:00

79 lines
1.7 KiB
Go

/*
* Copyright (c) 2018 DeineAgentur UG https://www.deineagentur.com. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for full license information.
*/
package gotext
// Translation is the struct for the Translations parsed via Po or Mo files and all coming parsers
type Translation struct {
ID string
PluralID string
Trs map[int]string
}
// NewTranslation returns the Translation object and initialized it.
func NewTranslation() *Translation {
tr := new(Translation)
tr.Trs = make(map[int]string)
return tr
}
// Get returns the string of the translation
func (t *Translation) Get() string {
// Look for Translation index 0
if _, ok := t.Trs[0]; ok {
if t.Trs[0] != "" {
return t.Trs[0]
}
}
// Return untranslated id by default
return t.ID
}
// GetN returns the string of the plural translation
func (t *Translation) GetN(n int) string {
// Look for Translation index
if _, ok := t.Trs[n]; ok {
if t.Trs[n] != "" {
return t.Trs[n]
}
}
// Return untranslated singular if corresponding
if n == 0 {
return t.ID
}
// Return untranslated plural by default
return t.PluralID
}
// Get returns the string of the translation. The second return value is true
// iff the string was found.
func (t *Translation) GetE() (string, bool) {
// Look for Translation index 0
if _, ok := t.Trs[0]; ok {
if t.Trs[0] != "" {
return t.Trs[0], true
}
}
return "", false
}
// GetN returns the string of the plural translation. The second return value
// is true iff the string was found.
func (t *Translation) GetNE(n int) (string, bool) {
// Look for Translation index
if _, ok := t.Trs[n]; ok {
if t.Trs[n] != "" {
return t.Trs[n], true
}
}
return "", false
}