printer.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. func (p *Printer) Print(key string) string {
  10. if dict, err := getTranslationDict(p.language); err == nil {
  11. if str, ok := dict[key]; ok {
  12. if translation, ok := str.(string); ok {
  13. return translation
  14. }
  15. }
  16. }
  17. return key
  18. }
  19. // Printf is like fmt.Printf, but using language-specific formatting.
  20. func (p *Printer) Printf(key string, args ...any) string {
  21. translation := key
  22. if dict, err := getTranslationDict(p.language); err == nil {
  23. if str, ok := dict[key]; ok {
  24. if translation, ok = str.(string); !ok {
  25. translation = key
  26. }
  27. }
  28. }
  29. return fmt.Sprintf(translation, args...)
  30. }
  31. // Plural returns the translation of the given key by using the language plural form.
  32. func (p *Printer) Plural(key string, n int, args ...interface{}) string {
  33. dict, err := getTranslationDict(p.language)
  34. if err != nil {
  35. return key
  36. }
  37. if choices, found := dict[key]; found {
  38. var plurals []string
  39. switch v := choices.(type) {
  40. case []string:
  41. plurals = v
  42. case []any:
  43. for _, v := range v {
  44. plurals = append(plurals, fmt.Sprint(v))
  45. }
  46. default:
  47. return key
  48. }
  49. index := getPluralForm(p.language, n)
  50. if len(plurals) > index {
  51. return fmt.Sprintf(plurals[index], args...)
  52. }
  53. }
  54. return key
  55. }
  56. // NewPrinter creates a new Printer.
  57. func NewPrinter(language string) *Printer {
  58. return &Printer{language}
  59. }