// Package i18n holds gitfed-web's translation strings and looks them up by
// key. Every page's copy lives here instead of being hardcoded in the Go
// templates, so the web UI can be served in more than one language.
package i18n
import "fmt"
// Lang is a supported UI language. New languages are added by defining a
// constant here and a dictionary for it in dict().
type Lang string
const (
EN Lang = "en"
FR Lang = "fr"
)
// Default is used whenever a request carries no usable language signal
// (no cookie, no matching Accept-Language tag).
const Default = EN
// ParseLang validates a language tag from a cookie or path segment,
// returning ok=false for anything gitfed doesn't have a dictionary for.
func ParseLang(v string) (Lang, bool) {
switch Lang(v) {
case EN, FR:
return Lang(v), true
default:
return "", false
}
}
func dict(l Lang) map[string]string {
if l == FR {
return fr
}
return en
}
// T looks up key in lang's dictionary, falling back to English and then to
// the key itself so a missing translation shows up as an obviously-wrong
// string instead of a blank. With extra args, the result is passed through
// fmt.Sprintf.
func T(lang Lang, key string, args ...any) string {
s, ok := dict(lang)[key]
if !ok {
s, ok = en[key]
}
if !ok {
s = key
}
if len(args) > 0 {
return fmt.Sprintf(s, args...)
}
return s
}