Skip to content

Languages (i18n) ​

The admin panel speaks English and Vietnamese (en, vi). Only the interface is translated: the content you manage stays in the language it was written in. Your own labels (resources, fields, actions, pages, settings) are English source strings that a catalog per language translates.

A resource list and form in VietnameseA RustCMS demo application: the posts list in Vietnamese.

Quick start ​

toml
# config/app.toml
locale = "en"              # the default language
locales = ["en", "vi"]     # what users may choose
toml
# lang/vi.toml
"Post" = "Bài viết"
"Posts" = "Bài viết"
rust
// src/providers/admin_panel_provider.rs
AdminProvider::new().translations("vi", include_str!("../../lang/vi.toml"))
sh
rustcms lang:missing vi     # lists what no catalog translates yet

A new application already registers lang/vi.toml this way.

Full example ​

The demo's catalog: global strings, then strings for one resource only.

toml
"Post" = "Bài viết"
"Posts" = "Bài viết"
"Categories" = "Danh mục"
"Attributes" = "Thuộc tính"
"Publishing" = "Xuất bản"
"Display" = "Hiển thị"
"Publish" = "Xuất bản"
"Publish the selected posts?" = "Xuất bản các bài viết đã chọn?"
toml
[posts]
# "Content" is also a navigation group; on the post form it is the first tab.
"Content" = "Nội dung"
rs
// Vietnamese labels (`cargo run -- lang:missing vi` lists what is missing).
.translations("vi", include_str!("../../lang/vi.toml"))

A hook's message translated with ctx.t, from the LMS settings page:

rs
async fn validate(ctx: &rustcms::admin::Ctx, settings: &Self) -> Result<(), rustcms::ValidationErrors> {
    if !(1..=MAX_CAPACITY).contains(&i64::from(settings.default_capacity)) {
        return Err(rustcms::ValidationErrors::field("default_capacity", ctx.t("must be between 1 and 10000")));
    }
    Ok(())
}

Which language a user sees ​

  1. The language the user chose on their account page (users.locale), if the deployment still offers it;
  2. else the browser's language (Accept-Language), if offered;
  3. else app.locale.

Accept-Language is read as browsers send it: the first 20 entries, by quality (q=), ties in the browser's order; vi-VN falls back to vi.

GET {admin}/api/auth/me returns that language as locale, the user's saved choice as preferredLocale (null: follow the browser) and the offered languages as locales; the panel switches to locale. The panel then sends the language it shows (X-Rustcms-Locale) with every request, and labels come back in that language, so what a tab caches always matches what it shows (another tab may have just switched). Record pages and the dashboard's recent-records widget format dates in that language too: instants in the browser's time zone, which is named; dates and local date-times as stored (inputs).

The choice is saved with POST {admin}/api/auth/locale {"locale": "vi"} (null: follow the browser). It answers {"locale": …}, the language now shown, or 422 for a language that is not offered. It is not a credential change: sessions and tokens stay valid. Before signing in, the login page offers the same choice, kept in the browser.

The language selector on the Account pageA RustCMS demo application: choosing a language.

Configuration ​

KeyDefault
app.locale"en"the language when nothing else decides; must be one of app.locales
app.locales["en", "vi"]what users may choose; language tags among the panel's own (en, vi)

The boot stops when app.locale is not in app.locales, when a tag is malformed, or when app.locales lists a language the panel is not written in. Applications cannot add a panel language. Both keys can also be set with RUSTCMS_APP__LOCALE and RUSTCMS_APP__LOCALES (Configuration).

Translating your labels ​

Labels of resources, fields, columns, filters, options, tabs, sections, actions and relations are English source strings, and so are the labels of settings pages, custom pages and slots, dashboard widgets and the Roles page's areas, permissions and presets. A catalog maps them to translations; labels formed from column names (published_at → "Published at") are translated the same way.

toml
# lang/vi.toml
"Post" = "Bài viết"
"Posts" = "Bài viết"            # the plural: `.plural()` or "<label>s"
"Publish the selected posts?" = "Xuất bản các bài viết đã chọn?"

[posts]                          # this resource only
"Title" = "Tiêu đề bài viết"
  • The catalog is compiled into the binary (no file to deploy).
  • Lookup: your catalog (the resource's table, then the global strings), then the framework's catalog (common field names and its own resources, also scoped first), else the source string.
  • A translation must keep the {placeholders} of its source; {{ and }} write braces. A malformed catalog or a language registered twice stops the boot. An empty translation ("Title" = "") counts as missing.
  • Data, identifiers (slugs, field names, permission names) and role names are never translated. Permission groups get a translated groupLabel: a resource's plural label, or the group in words (users → "Users").

Finding what is missing ​

rustcms lang:missing vi lists the labels no catalog translates, as TOML to fill in, and exits with an error while any is missing (useful in CI). It lists:

  • resource labels, each checked in its resource's table and then globally;
  • settings pages, custom page and slot labels, and every t("…") with a string literal in your templates;
  • dashboard widget labels;
  • permission groups that are not resources;
  • the Roles page's area, permission and preset labels and descriptions.

The output is one list of source strings without duplicates and without [resource] tables: add a scoped translation yourself when a resource needs its own. It refuses a language that is not in app.locales. Messages your hooks build at run time are not listed: translate them with ctx.t("…") (ctx.t_in(slug, "…") looks in the resource's table first), and add them to the catalog yourself.

In your code ​

Where
ctx.t(text), ctx.t_in(slug, text)hooks, actions, policies, data of pages and slots, settings validate
ctx.locale, principal.localethe request's language
{{ t("…") }}, localepage and slot templates (Customizing)
rustcms::i18n::{Translator, Tr, negotiate}the catalogs and the negotiation above, for your own code

New server validation messages of the framework need a template in rustcms::i18n::TEMPLATES; your own messages work without one (code custom).

Validation messages ​

Messages stay English on the wire (errors, formErrors, message), so API clients see what they always did. Each message also has a stable code and its parameters (text), which the panel translates:

json
{"message": "The given data was invalid.", "code": "validation_failed",
 "errors": {"title": ["may not be longer than 200 characters"]},
 "issues": {"title": [{"code": "max_length", "params": {"max": "200"}}]},
 "formErrors": [], "formIssues": []}

A message that follows none of the framework's templates (your own text) has the code custom and is shown as written: translate it with ctx.t where you build it. Conflicts (409) carry a reason, for example busy, upload_expired or receipt_expired. The codes and their English templates are listed in Error codes.

A validation error shown in VietnameseA RustCMS demo application: a translated validation message.

Mail ​

Account mails use the recipient's saved language when it is offered. Otherwise a password reset uses the language of the request that asked for it (when offered), and an invitation uses app.locale. The settings page's test mail uses the language of the user who sends it. Your own mails choose their locale when they render a template (Mail).

Extensions ​

Scripts get the panel's language and translate their own text from catalogs they register while loading. This works the same for widgets, pages, slots and cells (v1 ctx.locale and ctx.t) and for React components (props.locale and props.t). update (v1) is called, or the component re-renders, when the language changes. Props are never translated.

js
window.rustcms.registerTranslations("vi", { None: "Không màu" });

The demo's color widget registers its catalog first:

js
window.rustcms.registerTranslations("vi", {
  None: "Không màu",
  Red: "Đỏ",
  Green: "Xanh lá",
  Blue: "Xanh dương",
  Purple: "Tím",
});
window.rustcms.registerWidget("demo/color", {
  apiVersion: 1,
  mount(element, ctx) {
    let current = ctx;
    const group = document.createElement("div");
    group.className = "demo-color";
    group.setAttribute("role", "group");
    const buttons = (ctx.props?.palette ?? []).map(({ value, label }) => {
      const button = document.createElement("button");
      button.type = "button";
      button.className = "demo-color-swatch";
      button.dataset.color = value;
      button.dataset.label = label;
      button.addEventListener("click", () => current.onChange(value));
      return button;
    });
    const clear = document.createElement("button");
    clear.type = "button";
    clear.className = "demo-color-clear";
    clear.addEventListener("click", () => current.onChange(null));
    group.append(...buttons, clear);
    element.append(group);
    const render = () => {
      group.id = current.id;
      group.setAttribute("aria-label", current.label);
      // Labels in the panel's language (`update` is called when it changes).
      for (const button of buttons) {
        const label = current.t(button.dataset.label);
        button.setAttribute("aria-label", label);
        button.title = label;
      }
      clear.textContent = current.t("None");
      if (current.describedBy) group.setAttribute("aria-describedby", current.describedBy);
      else group.removeAttribute("aria-describedby");
      for (const button of [...buttons, clear]) button.disabled = current.disabled;
      for (const button of buttons) button.setAttribute("aria-pressed", String(button.dataset.color === current.value));
      clear.setAttribute("aria-pressed", String(current.value == null));
      group.classList.toggle("demo-color-invalid", current.invalid);
    };
    render();
    return {
      update(next) {
        current = next;
        render();
      },
      unmount() {
        group.remove();
      },
    };
  },
});

The panel's own text ​

The panel's interface ships in English and Vietnamese; app.locales must be chosen among them.

RustCMS 0.17.0 · source cfb82fa33fab · MIT OR Apache-2.0