You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8KB

  1. package gotext
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. )
  7. type Locale struct {
  8. // Path to locale files.
  9. path string
  10. // Language for this Locale
  11. lang string
  12. // List of available domains for this locale.
  13. domains map[string]*Po
  14. }
  15. // NewLocale creates and initializes a new Locale object for a given language.
  16. // It receives a path for the i18n files directory (p) and a language code to use (l).
  17. func NewLocale(p, l string) *Locale {
  18. return &Locale{
  19. path: p,
  20. lang: l,
  21. domains: make(map[string]*Po),
  22. }
  23. }
  24. // AddDomain creates a new domain for a given locale object and initializes the Po object.
  25. // If the domain exists, it gets reloaded.
  26. func (l *Locale) AddDomain(dom string) {
  27. po := new(Po)
  28. // Check for file.
  29. filename := path.Clean(l.path + string(os.PathSeparator) + l.lang + string(os.PathSeparator) + dom + ".po")
  30. // Try to use the generic language dir if the provided isn't available
  31. if _, err := os.Stat(filename); err != nil {
  32. if len(l.lang) > 2 {
  33. filename = path.Clean(l.path + string(os.PathSeparator) + l.lang[:2] + string(os.PathSeparator) + dom + ".po")
  34. }
  35. }
  36. // Parse file.
  37. po.ParseFile(filename)
  38. // Save new domain
  39. if l.domains == nil {
  40. l.domains = make(map[string]*Po)
  41. }
  42. l.domains[dom] = po
  43. }
  44. // Get uses a domain "default" to return the corresponding translation of a given string.
  45. func (l *Locale) Get(str string, vars ...interface{}) string {
  46. return l.GetD("default", str, vars...)
  47. }
  48. // GetD returns the corresponding translation in the given domain for a given string.
  49. func (l *Locale) GetD(dom, str string, vars ...interface{}) string {
  50. if l.domains != nil {
  51. if _, ok := l.domains[dom]; ok {
  52. if l.domains[dom] != nil {
  53. return l.domains[dom].Get(str, vars...)
  54. }
  55. }
  56. }
  57. // Return the same we received by default
  58. return fmt.Sprintf(str, vars...)
  59. }