Reference · Translations
locale_from
locale_from(fn) -> nullWhat 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:
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:
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"))nullen bEdge cases
- Outside a request the rule is not consulted:
locale()is the default locale, andwith_localesets it directly. - The function is called once per request, on the first use of
torlocale, and its answer is kept for the request. - Declaring it again replaces the rule; declaring it before
translationsis fine, since it is only read in a request. - It gives
null.
print(locale_from((request) => "fr"))translations({ en: { a: "b" }, fr: { a: "c" } })print(locale(), t("a"))print(with_locale("fr", () => t("a")))nullen bcErrors
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.
locale_from("fr")line 1: `locale_from` expects a function of the request, got strChaining
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:
translations("locales")locale_from((request) => request.query.lang ?? session().user.locale)See also
translations, locale, with_locale, t, set_cookie
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