
# Laralocale for Laravel Rust
<p align="center">
<a href="https://github.com/edulazaro/laralocale-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laralocale-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
<a href="https://crates.io/crates/laralocale"><img src="https://img.shields.io/crates/v/laralocale" alt="Crates.io"></a>
<a href="https://crates.io/crates/laralocale"><img src="https://img.shields.io/crates/d/laralocale" alt="Downloads"></a>
<a href="https://docs.rs/laralocale"><img src="https://img.shields.io/docsrs/laralocale" alt="Docs.rs"></a>
<a href="https://github.com/edulazaro/laralocale-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laralocale" alt="License"></a>
</p>
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](https://github.com/laravel/rust-framework/pull/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](#moving-to-laravels-own-localization).
```rust
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
```bash
cargo add laralocale
```
Register the service provider in `src/app.rs`:
```rust
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`:
```ini
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`:
```rust
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:
```rust
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:
```rust
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`.
| `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:
```rust
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:
```rust
middleware.replace(EncryptCookies::except(["locale"]));
```
For the `api` group, or a single route, attach it yourself:
```rust
the `minijinja` feature of Laravel Rust, which is also on by default.
## Configuration
`LocaleConfig` is the configuration section. Set it with `with_config`:
| `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 |
```rust
`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](https://github.com/laravel/rust-framework/pull/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::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](https://github.com/edulazaro/laratext-rust)'s job.
## Testing
```rust
#[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:
<p>
<a href="https://kenodo.com"><img src="art/logo-kenodo.png" width="24" alt="Kenodo"></a> <a href="https://kenodo.com">Kenodo</a>
<a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a> <a href="https://andorradev.com">AndorraDev</a>
</p>
## Author
Created by [Edu Lazaro](https://edulazaro.com)
## License
Laralocale for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).