printer.go 1.5 KB

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