Phoenix Localization

I am developing a multilingual application using the Phoenix Framework

So far, the router looks 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 plugin in the docs: http://www.phoenixframework.org/docs/understanding-plug#section-module-plugs

And to make the “locale” permanent in the application, I used a 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 have to add the above custom action and change each action in the new controller to enter locale

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

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

There are two things that I struggle with:

1 - Is this right? or am I confusing something?

2 - // "/: locale" , : "ru" ?

url: "example.com/en"

Kayne

+4
1

Phoenix Elixir , , Plug . Plug , , /:locale. Phoenix . :

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

Plug , .

, !

+1

Source: https://habr.com/ru/post/1628993/


All Articles