Skip to main content

localized

Function localized 

Source
pub fn localized<S: Clone + Send + Sync + 'static>(
    pages: Router<S>,
) -> Router<S>
Expand description

Serves pages in every locale: /path in the default locale, /<code>/path in the others.

For public pages search engines index in each language (Rails’ scope "(:locale)"), with the catalog declared unprefixed_default (ocre::locales!("en", "fr"; unprefixed_default)): the URL decides the language, so each page has one address per locale for hreflang (I18n::alternate_links).

  • /pricing is the default locale’s page. A visitor whose locale cookie or Accept-Language prefers another locale of the app gets a 303 See Other to it (/fr/pricing); crawlers send neither, so they index each URL in its own language. Only GET and HEAD are redirected.
  • /fr/pricing is French, and remembers the choice in the locale cookie, so the visitor’s next unprefixed URL leads back to French.
  • /en/pricing (the default locale’s code) answers 308 Permanent Redirect to /pricing; an unknown code (/xx/pricing) is a 404.

Pages outside localized keep the usual choice (cookie, then Accept-Language). A language switcher sets the cookie with I18n::cookie and links to I18n::path. No billed resource is used: headers only.

§Errors

A request answers 500 when layer is missing or the catalog is not declared unprefixed_default; the log line names the fix.

§Examples

use std::sync::LazyLock;
use axum::{Router, routing::get};
use ocre::{Ctx, i18n::{Catalog, I18n, Locales}};

static LOCALES: Locales =
    LazyLock::new(|| Catalog::load(&[("en", "en:\n  title: Pricing\n"), ("fr", "fr:\n  title: Tarifs\n")]).unprefixed_default());

async fn pricing(i18n: I18n) -> String {
    i18n.t("title").to_string()
}

fn routes() -> Router<Ctx> {
    let pages = Router::new().route("/pricing", get(pricing));
    Router::new()
        .merge(ocre::i18n::localized(pages)) // /pricing, /fr/pricing
        // ocre:routes
        .layer(ocre::i18n::layer(&LOCALES))
}