How to set a locale in Phoenix, to get to use priv/gettext/{lang}/LC_MESSAGES/errors.po?
As a test, I built the locale file with mix gettext.merge priv/gettext --locale ja
, and translated some words in it.
It works if I explicitly call put_locale/2
in web/views/error_helpers.ex
and <%= translate_error(message) %>
in a template file, but it's a bit ugly, in a point of DRY.
def translate_error(msg) do
Gettext.put_locale(LoginStudy.Gettext, "ja")
Gettext.dgettext(LoginStudy.Gettext, "errors", msg)
end
Is there any better way to set the default locale? I specified the default_locale
in config/config.ex
, but it doesn't work.
config :login_study, LoginStudy.Endpoint, default_locale: "ja",
Best Regards,
Great questions @hykw! Since Gettext support in Phoenix is new, documentation is just now starting to show up.
A good starting point is this excellent blog post by Rebecca Skinner: http://sevenseacat.net/2015/12/20/i18n-in-phoenix-apps.html
For example, if you want to set the locale to japanese only for some of your web requests, you can define a plug, as she did with MyApp.Locale
, and run it at the beginning of your request lifecycle. I just don't advise to store the locale in the session but keep it rather as part of the URL or some other parameter.
However, if you want the locale to always be japanese, you can write in your config file:
config :my_app, MyApp.Gettext, default_locale: "ja"
You can find more information about this on the Gettext docs: http://hexdocs.pm/gettext/Gettext.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With