laralocale 0.1.0

The current locale for Laravel Rust, with the API of laravel::lang: locale, set_locale, locales, negotiate and preferred_locale.
Documentation

Laralocale for Laravel Rust

Laralocale for Laravel Rust

The current locale, per request, with the API of Laravel Rust's own localization.

Laravel Rust 0.1 has no localization. Its prototype, which Taylor Otwell has open as a draft (PR #309), adds a laravel::lang module with locale, set_locale, locales and negotiate, and a request.preferred_locale() method. This crate has those names and that behaviour today, so that when the framework ships its own, you switch from laralocale:: to laravel::lang:: by changing little more than the use. See Moving to Laravel's own localization.

use laralocale::PreferredLocale;

laralocale::set_locale(request.preferred_locale());  // for the rest of the request
laralocale::locale();                                // "es"
laralocale::locales();                               // ["en", "ca", "es"]

There is no PHP package behind it: Laravel itself holds the locale in PHP. It is the shared base of the Laravel Rust ports of Laratext, Laralang and Larablog, and it works on its own. It targets Laravel Rust 0.1, which is in beta, and its API follows the framework's changes until 1.0.

Installation

cargo add laralocale

Register the service provider in src/app.rs:

use laralocale::LaralocaleServiceProvider;
use laravel::Application;

pub fn configure() -> ApplicationBuilder {
    Application::configure().with_providers(|providers| {
        providers.add(LaralocaleServiceProvider::new());
    })
}

The provider adds the configuration, a LocaleScope middleware at the start of the global middleware, which gives each request a locale of its own, and the locale() function in the views.

The languages are the ones your application has: the APP_LOCALE language, en by default, plus one for each {locale}.json file in the lang directory, as in the framework's prototype. Set APP_LOCALE and APP_FALLBACK_LOCALE in your .env:

APP_LOCALE=en
APP_FALLBACK_LOCALE=en

Choosing the language of a request

Each request starts in APP_LOCALE. To answer a visitor in another language, call set_locale in a middleware. Most applications choose it from the browser's Accept-Language header, and request.preferred_locale() returns the language the header prefers among the ones your application speaks. A browser asking for es-MX gets your es. Create src/http/middleware/localize.rs:

use laralocale::PreferredLocale;
use laravel::http::{Next, Request, Response, middleware};

#[middleware]
pub async fn localize(request: Request, next: Next) -> Response {
    laralocale::set_locale(request.preferred_locale());

    next.run(request).await
}

Then append it to the global middleware in src/app.rs, so it runs on every request:

.with_middleware(|middleware, _| {
    middleware.append(localize);
})

If your users pick a language in their settings, set that one instead, such as from a locale column on your users table. To read the current language, such as for the lang attribute of your page, call laralocale::locale(), or use locale() in a template.

set_locale applies to the rest of the request, whoever calls it: the handler, the views and the middleware that run later. Requests running at the same time each keep their own. Nothing is validated, so it accepts a locale your application does not have.

The functions

Function Returns
locale() The current language: the one set_locale chose, or APP_LOCALE
set_locale(locale) Sets the language of the rest of the request, command or job
locales() The languages the app speaks: APP_LOCALE, then the lang directory's files, sorted. The supported list of LocaleConfig replaces them when it is set
negotiate(&preferred) The language that best matches a list of tags, most preferred first, or APP_LOCALE when none does
fallback_locale() APP_FALLBACK_LOCALE
candidates(locale) The languages to look in for a locale: pt_BR, pt, then the fallback. For packages that translate
with_locale(locale, future) Runs a future in a language. For jobs, commands and tests
request.preferred_locale() negotiate applied to Accept-Language, honouring q-values. Needs use laralocale::PreferredLocale;

negotiate compares without regard to case, and - counts as _. es-MX matches your es, pt matches your pt_BR, an exact match wins over one of the same language, and the * wildcard stands for APP_LOCALE. It returns the language spelled as your application spells it, such as pt_BR.

locales() reads the lang directory each time it is called. Outside the application it is just the default language.

set_locale needs somewhere to keep the language: a request, which the provider scopes, or with_locale. Anywhere else the call is ignored and a warning is logged, and locale() returns APP_LOCALE.

Jobs, commands and tests

laralocale::with_locale("es", async {
    send_the_newsletter().await?;

    Ok::<_, laravel::Error>(())
})
.await?;

with_locale runs a future in a language and restores the previous one when it ends. Scopes nest, and a set_locale inside one does not leak into the one around it. It has no equivalent in the prototype, which keeps the language in the application context instead of in a task-local.

The locale is a tokio task-local. A task started with tokio::spawn does not inherit it, and neither does laravel::task::spawn: wrap the spawned future in with_locale too.

Detecting the locale from more than the header

DetectLocale is a convenience that the prototype does not have. It picks the locale of a request from the query string, the session, a cookie or the Accept-Language header, for sites where the visitor can choose a language and have it remembered. If the browser's header is all you need, use preferred_locale() as above.

Add it with with_detection(), which appends it to the web group after the session starts:

providers.add(LaralocaleServiceProvider::new().with_detection());

It tries the detect.sources in order and takes the first value that is one of your locales(). A value that is not is skipped, and when no source yields one the request gets APP_LOCALE. A middleware of yours that runs after it can still call set_locale.

Source Reads
Query The detect.query parameter, ?locale=es by default. The last one wins
Session The detect.session key of the session
Cookie The detect.cookie cookie
Header Accept-Language, best q-value first. q=0 and * are ignored

The default order is query, session, cookie, header. Change it:

use laralocale::{DetectSource, LocaleConfig};

config.section_mut::<LocaleConfig>().detect.sources = vec![DetectSource::Header];

The middleware only reads. It does not remember the locale: to keep a choice, put it in the session or in a cookie yourself, under the names in detect.

Cookies on the web group are encrypted. The cookie must be one your application set (for example response.with_cookie(Cookie::new("locale", "es"))), because a plain cookie that fails to decrypt reads as absent. To let a plain cookie, such as one a script writes, through, exclude it:

middleware.replace(EncryptCookies::except(["locale"]));

For the api group, or a single route, attach it yourself:

Application::configure().with_middleware(|middleware, _| {
    middleware.api(|api| {
        api.append(laralocale::DetectLocale);
    });
})

Templates

<html lang="{{ locale() }}">

locale() is laralocale::locale(). It needs the minijinja feature, which is on by default, and the minijinja feature of Laravel Rust, which is also on by default.

Configuration

LocaleConfig is the configuration section. Set it with with_config:

Key Default
locale en The default locale. Read from APP_LOCALE
fallback_locale en The locale translations fall back to. Read from APP_FALLBACK_LOCALE
supported [] The languages the app speaks. Empty means APP_LOCALE plus the lang directory
detect.sources query, session, cookie, header The sources of DetectLocale, in order
detect.session locale The session key
detect.cookie locale The cookie name
detect.query locale The query parameter
.with_config(|config, _| {
    config.section_mut::<LocaleConfig>().supported = ["en", "es", "ca"].map(str::to_owned).to_vec();
})

Set supported when you want to name the languages yourself instead of reading them from lang, such as when a language has no translation file but your routes or blog have it.

For other packages

A package that translates reads the locale and nothing else:

let locale = laralocale::locale();
let places = laralocale::candidates(&locale);

A middleware that sets the locale from the URL prefix, as Laralang does, wraps the request in with_locale or calls set_locale before passing it on, and every locale() after it, in the handler and in the views, returns the new value for that request only.

Moving to Laravel's own localization

The prototype is a draft (PR #309, branch localization) and may change before it lands, or not land. The mapping below is against its first commit. Check the framework's documentation when it ships.

laralocale laravel::lang
laralocale::locale() lang::locale()
laralocale::set_locale("es") lang::set_locale("es")
request.preferred_locale() with use laralocale::PreferredLocale; request.preferred_locale(), a method of Request
laralocale::locales() lang::locales(&context), hidden from the docs in the prototype
laralocale::negotiate(&tags) lang::negotiate(&context, &tags), hidden as well
laralocale::fallback_locale() laravel::config().app.fallback_locale, from APP_FALLBACK_LOCALE
laralocale::candidates("pt_BR") Private in the prototype, with the same chain
LocaleConfig::locale laravel::config().app.locale, from APP_LOCALE
laralocale::with_locale(..) None. Call lang::set_locale in the job or command
locale() in a template None in the prototype. Pass lang::locale() to the view
DetectLocale None. Write a middleware around set_locale
LaralocaleServiceProvider Not needed

The differences to expect:

  • Where the language lives. The prototype stores it in the application context, and panics when a function is called outside the application. Here it is a task-local: outside a request, locale() returns APP_LOCALE and set_locale is ignored with a warning.
  • Queued jobs. The prototype remembers the language a job was queued in. This crate does not.
  • locales() and negotiate() take no context here. In the prototype they take a Context, and are #[doc(hidden)], so request.preferred_locale() is the stable way in.
  • Translations are the framework's. The prototype also has lang::get! and the JSON files. This crate holds only the language: translating is Laratext's job.

Testing

#[laravel::test(app = app)]
async fn the_header_sets_the_locale(app: Application) {
    app.get("/")
        .header("accept-language", "es-ES,es;q=0.9,en;q=0.8")
        .await
        .assert_see("es");
}

Use app.scope(async || { with_locale("es", async { .. }).await }) for code that runs outside a request. Test requests send cookies as plain text, whatever the encryption of the group.

Differences from Laravel

There is no PHP package to differ from, so these are the differences from Laravel's own locale API.

  • Free functions, not App:: methods. App::getLocale() is laralocale::locale(), App::setLocale() is laralocale::set_locale() and App::getFallbackLocale() is laralocale::fallback_locale(). App::isLocale() and App::currentLocale() have no equivalent, in line with the prototype. with_locale replaces App::withLocale(), and takes a future instead of a closure.
  • The configuration is a typed section, LocaleConfig, not config('app.locale'). locale and fallback_locale read APP_LOCALE and APP_FALLBACK_LOCALE, as Laravel's config/app.php does.
  • The locale is per task, not per process. In PHP each request is a process, so the application holds the locale. Here the server handles requests concurrently, so each request carries its own in a task-local, and a spawned task does not inherit it.
  • set_locale needs a scope. Outside a request or with_locale there is nowhere to keep the locale, so the call is ignored with a warning, where Laravel would change the application.
  • Detection is optional. Laravel has no such middleware: Laralang's SetBrowserLocale and SetSessionLocale do this in PHP. DetectLocale is here for sites that remember a choice, and the URL prefix is Laralang's.
  • No Blade directive. The locale() function is the template side.

Sponsors

Laralocale for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:

Author

Created by Edu Lazaro

License

Laralocale for Laravel Rust is open-sourced software licensed under the MIT license.