Example

  1. package main
  2. import (
  3. "github.com/kataras/iris/v12"
  4. )
  5. func newApp() *iris.Application {
  6. app := iris.New()
  7. // Configure i18n.
  8. // First parameter: Glob filpath patern,
  9. // Second variadic parameter: Optional language tags, the first one is the default/fallback one.
  10. app.I18n.Load("./locales/*/*.ini", "en-US", "el-GR", "zh-CN")
  11. // app.I18n.LoadAssets for go-bindata.
  12. // Default values:
  13. // app.I18n.URLParameter = "lang"
  14. // app.I18n.Subdomain = true
  15. //
  16. // Set to false to disallow path (local) redirects,
  17. // see https://github.com/kataras/iris/issues/1369.
  18. // app.I18n.PathRedirect = true
  19. app.Get("/", func(ctx iris.Context) {
  20. hi := ctx.Tr("hi", "iris")
  21. locale := ctx.GetLocale()
  22. ctx.Writef("From the language %s translated output: %s", locale.Language(), hi)
  23. })
  24. app.Get("/some-path", func(ctx iris.Context) {
  25. ctx.Writef("%s", ctx.Tr("hi", "iris"))
  26. })
  27. app.Get("/other", func(ctx iris.Context) {
  28. language := ctx.GetLocale().Language()
  29. fromFirstFileValue := ctx.Tr("key1")
  30. fromSecondFileValue := ctx.Tr("key2")
  31. ctx.Writef("From the language: %s, translated output:\n%s=%s\n%s=%s",
  32. language, "key1", fromFirstFileValue,
  33. "key2", fromSecondFileValue)
  34. })
  35. // using in inside your views:
  36. view := iris.HTML("./views", ".html")
  37. app.RegisterView(view)
  38. app.Get("/templates", func(ctx iris.Context) {
  39. ctx.View("index.html", iris.Map{
  40. "tr": ctx.Tr, // word, arguments... {call .tr "hi" "iris"}}
  41. })
  42. // Note that,
  43. // Iris automatically adds a "tr" global template function as well,
  44. // the only difference is the way you call it inside your templates and
  45. // that it accepts a language code as its first argument.
  46. })
  47. //
  48. return app
  49. }
  50. func main() {
  51. app := newApp()
  52. // go to http://localhost:8080/el-gr/some-path
  53. // ^ (by path prefix)
  54. //
  55. // or http://el.mydomain.com8080/some-path
  56. // ^ (by subdomain - test locally with the hosts file)
  57. //
  58. // or http://localhost:8080/zh-CN/templates
  59. // ^ (by path prefix with uppercase)
  60. //
  61. // or http://localhost:8080/some-path?lang=el-GR
  62. // ^ (by url parameter)
  63. //
  64. // or http://localhost:8080 (default is en-US)
  65. // or http://localhost:8080/?lang=zh-CN
  66. //
  67. // go to http://localhost:8080/other?lang=el-GR
  68. // or http://localhost:8080/other (default is en-US)
  69. // or http://localhost:8080/other?lang=en-US
  70. //
  71. // or use cookies to set the language.
  72. app.Listen(":8080", iris.WithSitemap("http://localhost:8080"))
  73. }