Gettext Localization

Hello there, I’m trying to localize my app using Gettext. I extracted and merged the POT files and it works fine for the page.index.html.ex however when I navigate to any other route in my app the locale returns to English again, or I have to append ?locale=de and the end of the url to work fine.

Here is my config:

# Config Locales 
config :lean, LeanWeb.Gettext, locales: ~w(en de es), default_locale: "en"

and I wrote this plug:

defmodule LeanWeb.Plugs.SetLocale do
    import Plug.Conn

    @supported_locales Gettext.known_locales(LeanWeb.Gettext)

    def init(_options), do: nil 

    def call(%Plug.Conn{params: %{"locale" => locale}} = conn, _options) when locale in @supported_locales do 
        case fetch_locale_from(conn) do
            nil ->
            locale ->
                LeanWeb.Gettext |> Gettext.put_locale(locale)
                conn |> put_resp_cookie "locale", locale, max_age: 365*24*60*60

    defp fetch_locale_from(conn) do
        (conn.params["locale"] || conn.cookies["locale"]) |>

    defp check_locale(locale) when locale in @supported_locales, do: locale
    defp check_locale(_), do: nil

    def call(conn, _options), do: conn 


and added it to the :browser pipeline

pipeline :browser do
    plug :accepts, ["html"]
    plug LeanWeb.Plugs.SetLocale
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers

Can you help me with this?
Thanks in advance!

Although your code looks correct, You should not use your plug that high in the pipeline…

Try to put it at the end of the plug list… at least after the fetch session plug.

And yes, order might be important, when plugs depends on other plugs for example :slight_smile:

1 Like

Do you read from the session somewhere? You set the locale in the case you see the parameter, though I can’t see place that recovers the locale from the session if it’s not in the query.

1 Like

No, I don’t read from the session. I think you are right. Any help where and how should I read from session. It may be a noob question but I’m still new to phoenix. Thanks in advance.

I think it makes most sense in your current fall back clause to check for the session and either set the locale to the default or to whatever is in the session.

1 Like

I will try this, thank you for your time, much appreciated.

1 Like