table.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package i18n
  15. import (
  16. "context"
  17. "golang.org/x/text/language"
  18. "yunion.io/x/pkg/appctx"
  19. )
  20. type Tag = language.Tag
  21. var (
  22. I18N_TAG_CHINESE Tag = Tag(language.Chinese)
  23. I18N_TAG_ENGLISH Tag = Tag(language.English)
  24. )
  25. type ITable interface {
  26. Lookup(ctx context.Context, key string) string
  27. }
  28. type TableEntry map[language.Tag]string
  29. type Table map[string]TableEntry
  30. func NewTableEntry() TableEntry {
  31. return TableEntry{}
  32. }
  33. func (te TableEntry) CN(v string) TableEntry {
  34. te[language.Chinese] = v
  35. return te
  36. }
  37. func (te TableEntry) EN(v string) TableEntry {
  38. te[language.English] = v
  39. return te
  40. }
  41. func (te TableEntry) Lookup(ctx context.Context) (string, bool) {
  42. lang := appctx.Lang(ctx)
  43. lang = tableLangMatch(lang)
  44. v, ok := te[lang]
  45. return v, ok
  46. }
  47. func (tbl Table) Set(k string, te TableEntry) {
  48. tbl[k] = te
  49. }
  50. func (tbl Table) Lookup(ctx context.Context, key string) string {
  51. lang := appctx.Lang(ctx)
  52. return tbl.LookupByLang(lang, key)
  53. }
  54. func (tbl Table) LookupByLang(lang language.Tag, key string) string {
  55. te, ok := tbl[key]
  56. if !ok {
  57. return key
  58. }
  59. lang = tableLangMatch(lang)
  60. v, ok := te[lang]
  61. if !ok {
  62. return key
  63. }
  64. return v
  65. }
  66. var tableLangSupported = []language.Tag{
  67. language.English,
  68. language.Chinese,
  69. }
  70. var tableLangMatcher = language.NewMatcher(tableLangSupported)
  71. func tableLangMatch(tag language.Tag) language.Tag {
  72. _, i, _ := tableLangMatcher.Match(tag)
  73. return tableLangSupported[i]
  74. }