Reference · Translations

locale_from

signature
locale_from(fn) -> null

What it does

Declares how a request's locale is chosen: the function is given the request and gives a locale name (a query parameter, a signed-in user's setting), which is matched to the program's translations as Accept-Language is (fr-CA is served by fr). Anything else than a name that matches (null, an unknown locale) falls through to the usual choice: the locale cookie, then Accept-Language, then the default. Declare it at the top of the program, after translations.

Examples

A page in two languages, a link that switches, and the route that keeps the choice in the locale cookie, which is read when the rule gives nothing. /?lang=fr shows French whatever the cookie says, /?lang=de falls through to the cookie, then to Accept-Language:

in a program
translations({    en: { hello: "Hello", switch: "Français" },    fr: { hello: "Bonjour", switch: "English" },})locale_from((request) => request.query.lang)    // /?lang=fr, a link that shows Frenchroute GET / {    let other = locale() == "fr" ? "en" : "fr"    <main>        <h1>{t("hello")}</h1>        <a href={`/settings/lang/${other}`}>{t("switch")}</a>    </main>}route GET /settings/lang/:code {    set_cookie("locale", code, { max_age: "1y" })  // the choice, kept for the next visit    redirect("/")}

A signed-in user's setting, from the database:

in a program
translations("locales")locale_from((request) => db.one("select lang from users where id = ?", session().user)?.lang)
translations({ en: { a: "b" }, fr: { a: "c" } })print(locale_from((request) => request.query.lang))print(locale(), t("a"))
output
nullen b

Edge cases

print(locale_from((request) => "fr"))translations({ en: { a: "b" }, fr: { a: "c" } })print(locale(), t("a"))print(with_locale("fr", () => t("a")))
output
nullen bc

Errors

A value that is not a function is a runtime error, not an error value. A function that fails inside a request, or gives something that is not a string, counts as no answer: the usual choice is made.

this one fails
locale_from("fr")
output
line 1: `locale_from` expects a function of the request, got str

Chaining

It is a declaration, not a value, so it does not take part in pipelines. A rule that looks at a user reads the session:

in a program
translations("locales")locale_from((request) => request.query.lang ?? session().user.locale)

See also

translations, locale, with_locale, t, set_cookie

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On locale_from(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo