Phoenix integration for the Localize library providing plugs for locale discovery, compile-time route localization, and HTML form helpers for localized data.
Locale Discovery — detect the user's locale from the accept-language header, query parameters, URL path, session, cookies, hostname TLD, or custom functions.
Session Persistence — store the discovered locale in the session for subsequent requests and LiveView connections.
Compile-time Route Localization — translate route path segments using Gettext at compile time and generate localized routes for each configured locale.
Verified Localized Routes — the
~qsigil provides compile-time verified localized routes that dispatch to the correct translated path based on the current locale.HTML Form Helpers — generate
<select>tags and option lists for currencies, territories, territory subdivisions, locales, units of measure, and months with localized display names.
Add localize_web to your list of dependencies in mix.exs:
defdepsdo[{:localize_web,"~> 1.0"}]endAdd the locale plugs to your Phoenix browser pipeline after fetch_session:
pipeline:browserdoplug:accepts,["html"]plug:fetch_sessionplugLocalize.Plug.PutLocale,from: [:session,:accept_language,:query,:path],gettext: MyApp.GettextplugLocalize.Plug.PutSessionendLocalize.Plug.PutLocale reads the :session source with
Plug.Conn.get_session/2, so fetch_session must run first. If :cookie is
used outside a browser/session pipeline, fetch cookies before PutLocale;
fetch_session already does that in the browser pipeline.
Restore the locale in your LiveView on_mount callback:
defon_mount(:default,_params,session,socket)do{:ok,_locale}=Localize.Plug.put_locale_from_session(session,gettext: MyApp.Gettext){:cont,socket}endConfigure your router with localized routes:
defmoduleMyApp.RouterdousePhoenix.RouteruseLocalize.Routes,gettext: MyApp.Gettextlocalizedoget"/pages/:page",PageController,:showresources"/users",UserControllerendendProvide translations in priv/gettext/{locale}/LC_MESSAGES/routes.po for each path segment.
Use the ~q sigil for compile-time verified localized paths:
useLocalize.VerifiedRoutes,router: MyApp.Router,endpoint: MyApp.Endpoint,gettext: MyApp.Gettext# In templates:~q"/users"Generate localized select tags in your templates:
iex>Localize.HTML.Territory.select(:my_form,:territory,selected: :AU)iex>Localize.HTML.Currency.select(:my_form,:currency,selected: :USD)iex>Localize.HTML.Locale.select(:my_form,:locale,selected: "en")Full documentation is available on HexDocs.
The localized routing in this library is based on
ex_cldr_routeswhich was inspired by the work originally done by Bart Otten onPhxAltRoutes— which has evolved to the much enhanced Routex. Users seeking a more comprehensive and extensible localized routing solution should consider Routex as an alternative toLocalize.Routes.