gview_i18n.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gview
  7. import (
  8. "context"
  9. "github.com/gogf/gf/i18n/gi18n"
  10. "github.com/gogf/gf/util/gconv"
  11. )
  12. const (
  13. i18nLanguageVariableName = "I18nLanguage"
  14. )
  15. // i18nTranslate translate the content with i18n feature.
  16. func (view *View) i18nTranslate(ctx context.Context, content string, variables Params) string {
  17. if view.config.I18nManager != nil {
  18. // Compatible with old version.
  19. if language, ok := variables[i18nLanguageVariableName]; ok {
  20. ctx = gi18n.WithLanguage(ctx, gconv.String(language))
  21. }
  22. return view.config.I18nManager.T(ctx, content)
  23. }
  24. return content
  25. }
  26. // setI18nLanguageFromCtx retrieves language name from context and sets it to template variables map.
  27. func (view *View) setI18nLanguageFromCtx(ctx context.Context, variables map[string]interface{}) {
  28. if language, ok := variables[i18nLanguageVariableName]; !ok {
  29. if language = gi18n.LanguageFromCtx(ctx); language != "" {
  30. variables[i18nLanguageVariableName] = language
  31. }
  32. }
  33. }