Skip to content
This repository has been archived by the owner on May 8, 2024. It is now read-only.

A plug to parse the accept-language header and store a list of preferred locales.

License

Notifications You must be signed in to change notification settings

labtwentyfive/plug_preferred_locales

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PlugPreferredLocales

Build Status

Parses the accept-language header and sets the key :plug_preferred_locales of %Plug.Conn{} to a list of preferred locales.

Documentation

Documentation is available at HexDocs:

https://hexdocs.pm/plug_preferred_locales

Integration with gettext

If you use the Gettext package you can add something like this to your router pipeline:

defmodule MyappWeb.Router do
  use MyappWeb, :router

  pipeline :browser do
    # ....
    plug(PlugPreferredLocales, ignore_area: true)
    plug(:set_language)
  end

  def set_language(conn, _opts) do
    preferred_languages = MapSet.new(conn.private.plug_preferred_locales)

    available_languages =
      MyappWeb.Gettext
      |> Gettext.known_locales()
      |> MapSet.new()

    intersection = MapSet.intersection(preferred_languages, available_languages)

    if MapSet.size(intersection) > 0 do
      intersection
      |> MapSet.to_list()
      |> List.first()
      |> Gettext.put_locale()
    end

    conn
  end
end

Installation

If available in Hex, the package can be installed by adding plug_gettext to your list of dependencies in mix.exs:

def deps do
  [
    {:plug_preferred_locales, "~> 0.1.0"}
  ]
end