Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix Localization

I'm developing a multilingual application using the Phoenix Framework

So far, the router look like this:

scope "/:locale", App do
    pipe_through [:browser, :browser_session]

    get "/", PageController, :index

    get  "/otherpage", OtherpageController, :index
end

scope "/", App do

end

I used the plug in the docs : http://www.phoenixframework.org/docs/understanding-plug#section-module-plugs

And to make the "locale" persistent in the app, I used the custom action in the Phoenix.Controller module to do this:

def action(conn, _) do
    apply(__MODULE__, action_name(conn), [conn,
                                    conn.params,
                                    conn.assigns.locale])
end

so now every time I generated a controller I should add the above custom action, and change every action in the new controller to inject the locale

def index(conn, _params, locale) do
    list = Repo.all(List)

    render conn, "index.html", list: list
end

There are two things that I'm struggling with:

1 - Is this the right way ? or I'm messing something ?

2 - And how to make the scope "/" to be redirect to scope "/:locale" with a default value like: "en" ?

EDIT

I like to have this url: "example.com/en"

Kayne

like image 325
kayne Avatar asked Feb 16 '16 13:02

kayne


1 Answers

I'm new to Phoenix and Elixir myself but it seems to me a Plug would be the perfect solution for your second question. Use a Plug to modify the conn to for example redirect to /:locale. How to use Plugs to redirect is described in the Phoenix documentation here. I copied the redirect for localization plug part in the following:

defmodule HelloPhoenix.Plugs.Locale do
  import Plug.Conn

  @locales ["en", "fr", "de"]

  def init(default), do: default

  def call(%Plug.Conn{params: %{"locale" => loc}} = conn, _default) when loc in @locales do
    assign(conn, :locale, loc)
  end
  def call(conn, default), do: assign(conn, :locale, default)
end

defmodule HelloPhoenix.Router do
  use HelloPhoenix.Web, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug HelloPhoenix.Plugs.Locale, "en"
  end

When it comes to redirecting with a Plug this blog article is also a short and helpful resource.

I hope that helps!

like image 62
SSchneid Avatar answered Oct 14 '22 06:10

SSchneid