Reference · Translations
with_locale
with_locale(str, fn) -> anyWhat it does
Runs a function in another locale and gives what the function gives: t and
locale inside it use that locale, and the request's own locale is back afterwards.
For an email in the recipient's language, or a page that shows two. The name is
matched as Accept-Language is: fr-CA is served by fr, pt by pt-BR, without
regard to case; a name no locale serves runs the function in the default locale.
Examples
translations({ en: { bye: "Goodbye, {name}" }, fr: { bye: "Au revoir, {name}" },})print(with_locale("fr", () => t("bye", { name: "Ada" })))print(with_locale("fr", () => [locale(), t("bye", { name: "Ada" })]))print(locale())Au revoir, Ada["fr", "Au revoir, Ada"]enEdge cases
- The function's value comes back as it is, of any type; a function that takes no arguments is called with none.
- Calls nest: the inner locale wins inside, the outer is back after it.
- An unknown locale, or
"", runs the function in the default locale;fr_FRwith an underscore isfr. - A program's own named function works as the function.
translations({ en: { a: "b" }, fr: { a: "c" } })print(with_locale("fr", () => 42))print(with_locale("fr", () => with_locale("en", () => t("a")) + t("a")))print(with_locale("de", () => locale()), with_locale("", () => locale()), with_locale("fr_FR", () => locale()))fn greet() = t("a")print(with_locale("FR", greet))42bcen en frcErrors
Calling it before translations is a runtime error, not an error value; so is a name
that is not a string, a missing function, or a second argument that cannot be called.
An error the function raises is the caller's, and the locale is restored.
print(with_locale("fr", () => 1))line 1: `with_locale` needs `translations` firsttranslations({ en: { a: "b" } })print(with_locale("en"))line 2: `with_locale` needs a function to runChaining
The locale comes first, so in a pipeline the function is the only argument written; more often the call wraps a block, and a list of locales maps over it.
translations({ en: { a: "Hello" }, fr: { a: "Bonjour" }, de: { a: "Hallo" } })print("fr" | with_locale(() => t("a")))print(["en", "fr", "de"] | map((l) => with_locale(l, () => t("a"))))Bonjour["Hello", "Bonjour", "Hallo"]fn welcome_email(user) = with_locale(user.locale, () => { let subject = t("email.welcome.subject") let body = t("email.welcome.body", { name: user.name }) { subject, body }})See also
translations, t, locale, locale_from
Thread 0 posts
On with_locale(): 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