From 6ba3fc4b4c3f6946818f152f0d82499d9a1ce089 Mon Sep 17 00:00:00 2001 From: david-jones10 <45517096+david-jones10@users.noreply.github.com> Date: Tue, 10 Oct 2023 12:27:36 +0100 Subject: [PATCH 1/2] connect to Plug.Accepts to access Accept-Language Browser language is sent in request headers under Accept-Language. This change connects to the Plug.Accepts plug to allow the app to parse the Accepts headers, including the Accept-Language header. This will then give access to this information where the app decides which language to serve, to make a more accurate decision. --- lib/sign_dict_web/endpoint.ex | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/sign_dict_web/endpoint.ex b/lib/sign_dict_web/endpoint.ex index 1e8a9fb0..81f0ed6b 100644 --- a/lib/sign_dict_web/endpoint.ex +++ b/lib/sign_dict_web/endpoint.ex @@ -51,6 +51,7 @@ defmodule SignDictWeb.Endpoint do read_timeout: 60_000 ) + plug(Plug.Accepts) plug(Plug.MethodOverride) plug(Plug.Head) From 9313380d64f769fdbaa198064f40fcdedc8023df Mon Sep 17 00:00:00 2001 From: david-jones10 <45517096+david-jones10@users.noreply.github.com> Date: Tue, 10 Oct 2023 14:04:41 +0100 Subject: [PATCH 2/2] attempt to get user locale from accept header Updates get_user_locale to attempt to get locale from the HTTP request headers. If not, falls back to existing behaviour of attempting to read from conn object, finally returning nothing if none found. --- lib/sign_dict_web/plugs/locale.ex | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/sign_dict_web/plugs/locale.ex b/lib/sign_dict_web/plugs/locale.ex index db6edb72..27100c3b 100644 --- a/lib/sign_dict_web/plugs/locale.ex +++ b/lib/sign_dict_web/plugs/locale.ex @@ -27,8 +27,15 @@ defmodule SignDictWeb.Plug.Locale do end defp get_user_locale(conn) do - if conn.assigns[:current_user] do - conn.assigns[:current_user].locale + accept_language = Plug.Conn.get_req_header(conn, "accept-language") |> Plug.Conn.get_accept_language() + + case accept_language do + [locale | _rest] -> + locale + [] when conn.assigns[:current_user] -> + conn.assigns[:current_user].locale + _ -> + nil end end