I am supposed to create multi language website, therefore I am using gettext for this.
At first I created 3 language in my project and I made translations in it, but I couldn’t change default_locale like its document.
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug SetLocale, gettext: MultiLangWeb.Gettext, default_locale: "fa", cookie_key: "project_locale" #cookie_key is optional
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", MultiLangWeb do
pipe_through :browser # Use the default browser stack
get "/", PageController, :dummy
end
may you test my project in github because I can’t fix it? I think Gettext loads everything on config file and doesn’t show any reaction to put_locale/1 .
I have entered Gettext.get_locale(MultiLangWeb.Gettext) in terminal and Gettext.put_locale(MultiLangWeb.Gettext, "fa"), after that I have tested Gettext.get_locale(MultiLangWeb.Gettext) and it shows me fa, but I have a problem yet.
Had the same problem here ; I found few things on Google and ended up with that. Default language will be used until the user sends a locale in params, then it will be stored in a simple cookie. Just use it in your plug and you should be fine.
I tried to make it work with get_req_header(conn, “accept-language”), but never found how to do nor why I should use that…
@locales Gettext.known_locales(MyappWeb.Gettext)
def call(conn, _opts) do
case locale_from_params(conn) || locale_from_cookies(conn) do
nil ->
Gettext.put_locale("mr") # Language by default no handled by Gettext
conn
|> persist_locale("mr")
locale ->
Gettext.put_locale(locale)
conn
|> persist_locale(locale)
end
end
defp persist_locale(conn, new_locale) do
conn |> put_resp_cookie("locale", new_locale, max_age: 10 * 24 * 60 * 60)
end
defp locale_from_params(conn) do
conn.params["locale"] |> validate_locale
end
defp locale_from_cookies(conn) do
conn.cookies["locale"] |> validate_locale
end
defp validate_locale(locale) when locale in @locales, do: locale
defp validate_locale(_locale), do: nil
I followed this tutorial and it works for me: Phoenix I18n.
The difference I noticed at first glance between the way you’re setting default locale in config is that you don’t provide the full list of supported locales.
For example config :demo, I18ndemoWeb.Gettext, default_locale: ru, locales: ~w(en ru)
I hope it will heelp…
That works for me.