meta pixel

Phoenix Internationalization


    Posted by Iago Cavalcante

    on Apr 29th 2025


Solution

With LiveView 0.18 we can have functional components and easily trigger an event from our functional component and intercept them in a general way using LiveSession.

This was the simplest approach I could think of to share and modify the language of the page we are accessing.

With a global assign, we can access the current locale and modify the language of the page using the with_locale from gettext.

Attempt

First, we need to define a second language for our i18n tool (gettext). To do this, simply go to your project directory through the terminal and run the following command:

terminal mix gettext.merge priv/gettext --locale pt_BR

The chosen language was pt_BR, but it can be any available language you want to use.

With our new language set, we will now create our live session that will take care of setting our default language in the assigns for all live views and will have the method to handle language switching in the system.

Inside our _web folder, we will create a module called locale.ex, and it will have the following structure:

```elixir defmodule PhoenixI18nWeb.Locale do import Phoenix.LiveView use Phoenix.Component

def on_mount(:default, _params, _session, socket) do

{:cont,
 socket
 |> assign(:locale, "en")
 |> attach_hook(:set_locale, :handle_event, &handle_event/3)}

end

defp handleevent("togglelocale", %{"locale" => "en"}, socket) do locale = "ptBR" performassigns(socket, locale) end

defp handleevent("togglelocale", %{"locale" => "ptBR"}, socket) do locale = "en" performassigns(socket, locale) end

defp handleevent(, _, socket) do {:cont, socket} end

defp performassigns(socket, locale) do Gettext.putlocale(IagocavalcanteWeb.Gettext, locale) {:halt, socket |> assign(locale: locale)} end end ```

In the onmount function, we are setting the default locale to English and we have a hook that will be responsible for handling the language change event. We call it togglelocale.

With this done, we are ready to create our component that will call the hook that was added to the mount. It will have the following structure:

```elixir defmodule PhoenixI18nWeb.ToggleLocale do use Phoenix.Component

def togglelocale(assigns) do ~H""" """ end end ```

With this, now we just need to update our live view and add wherever we want to use Gettext with the chosen language the following code:

elixir <%= Gettext.with_locale(@locale, fn -> %> <%= gettext("Peace of mind from prototype to production.") %> <% end) %>

Finally, let's add our live session to the routes that we need to take care of for i18N:

elixir live_session :locale, on_mount: [PhoenixI18nWeb.RestoreLocale] do live "/", HomeLive, :home end

Iago CavalcanteTechnology Expert