printer.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package locale // import "miniflux.app/v2/internal/locale"
  4. import "fmt"
  5. // Printer converts translation keys to language-specific strings.
  6. type Printer struct {
  7. language string
  8. }
  9. // Printf is like fmt.Printf, but using language-specific formatting.
  10. func (p *Printer) Printf(key string, args ...interface{}) string {
  11. var translation string
  12. str, found := defaultCatalog[p.language][key]
  13. if !found {
  14. translation = key
  15. } else {
  16. var valid bool
  17. translation, valid = str.(string)
  18. if !valid {
  19. translation = key
  20. }
  21. }
  22. return fmt.Sprintf(translation, args...)
  23. }
  24. // Plural returns the translation of the given key by using the language plural form.
  25. func (p *Printer) Plural(key string, n int, args ...interface{}) string {
  26. choices, found := defaultCatalog[p.language][key]
  27. if found {
  28. var plurals []string
  29. switch v := choices.(type) {
  30. case []interface{}:
  31. for _, v := range v {
  32. plurals = append(plurals, fmt.Sprint(v))
  33. }
  34. case []string:
  35. plurals = v
  36. default:
  37. return key
  38. }
  39. pluralForm, found := pluralForms[p.language]
  40. if !found {
  41. pluralForm = pluralForms["default"]
  42. }
  43. index := pluralForm(n)
  44. if len(plurals) > index {
  45. return fmt.Sprintf(plurals[index], args...)
  46. }
  47. }
  48. return key
  49. }
  50. // NewPrinter creates a new Printer.
  51. func NewPrinter(language string) *Printer {
  52. return &Printer{language}
  53. }