How to determine the users preferred language?

Hi guys,
I made my app now multi-lingual, but would like to achieve that my app picks automatically the language that the user has set in his browser preferences. But I have no idea how to do this in Anvil.

So as far as I understand it, I need to read the Accept-Language header of the http-request:

Accept-Language: de,en-US;q=0.7,en;q=0.3

and return a html-document with either

<html lang="en-US">

or

<html lang="de">

depending on the settings in the Accept-Language header. So far so good, when you are on the server side. But Anvil is client code and Javascript. So how would I do this Anvil? Create a http_endpoint, read the request and do … ???

I use now the following workaround:

@anvil.server.callable
def get_preferred_locale():
  if not anvil.server.context.client.location.country in ['Germany','Austria',"Switzerland"]:
    return 'DE'
  return 'EN'

but still would like to know how my original problem is solved in Anvil.

You can get the browser locale using javascript:

function getNavigatorLanguage() {
if (navigator.languages && navigator.languages.length) {
return navigator.languages[0];
} else {
return navigator.userLanguage || navigator.language || navigator.browserLanguage || β€˜en’;
}
}

2 Likes