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