Internationalization

WebComPy's internationalization core ships as webcompy.i18n: a dependency-injected I18nManager holding a reactive locale Signal[str], nested message catalogs, and fallback rules, paired with the use_i18n() composable that exposes (locale, t, controller) to components.

Translations read locale.value inside normal reactive tracking and resolve initial locale exclusively from the webcompy-locale cookie and default_locale, so server-rendered HTML and browser hydration agree on the initial language without an extra transfer channel or post-hydration flash. (See the interactive i18n Playground example.)

When to use#

  • Need multi-language UI text synced across SSR/SSG HTML and the live browser session — use webcompy.i18n with cookie persistence.
  • Want browser-only preferences without affecting server-rendered HTML — use use_local_storage as described in Persistence Patterns.
  • Exposing browser events or external observables as read-only reactive views — see Read-only Signals and Events.

Setup#

Create message catalogs {locale: {nested dicts}} and provide an I18nManager factory under I18N_KEY during application setup:

from webcompy import use_computed
from webcompy.app import WebComPyApp, WebComPyAppConfig
from webcompy.components import ComponentContext, define_component
from webcompy.elements import html
from webcompy.i18n import I18N_KEY, I18nManager, use_i18n
from webcompy.template import render_template

CATALOGS = {
    "en": {
        "nav": {"home": "Home", "about": "About"},
        "greeting": "Hello, {name}!",
        "items": {"one": "{count} item", "other": "{count} items"},
    },
    "ja": {
        "nav": {"home": "ホーム", "about": "概要"},
        "greeting": "こんにちは、{name} さん!",
        "items": {"other": "{count} 個のアイテム"},
    },
}


@define_component()
def Navbar(context: ComponentContext[None]):
    locale, t, controller = use_i18n()

    return html.NAV(
        {"aria-label": use_computed(lambda: t("nav.home"))},
        render_template("<p>{{ t('nav.home') }}</p>", {"t": t}),
        html.BUTTON(
            {"@click": lambda _ev: controller.set("ja" if locale.value == "en" else "en")},
            use_computed(lambda: f"Locale: {locale.value}"),
        ),
    )


def make_i18n_manager() -> I18nManager:
    return I18nManager(
        CATALOGS,
        default_locale="en",
        supported_locales={"en", "ja"},
    )


app = WebComPyApp(root_component=Navbar, config=WebComPyAppConfig())
app.provide(I18N_KEY, make_i18n_manager)

Why provide a factory function rather than a pre-built I18nManager(...) instance:

  • Each RenderContext instantiates the manager lazily inside its own per-request / per-app DIScope after COOKIE_PORT_KEY (ServerCookiePort on SSR, BrowserCookiePort in the browser) has been registered.
  • Separate SSR requests never share a mutable locale signal.

Inside any component setup under that scope, use_i18n() returns (locale, t, controller):

  • locale — reactive Signal[str] holding the active locale tag.
  • t(key, *, count=None, **params) — resolves key against locale.value at call time. When render_template("... {{ t('nav.home') }} ...", {"t": t}) or use_computed(lambda: t("nav.home")) evaluates t(...), reading locale.value registers a normal reactive dependency so switching locales re-renders every bound translation automatically without any custom subscription API.
  • controller — I18nController exposing .locale (read-only property returning the current tag) and .set(locale) (normalizes, updates the signal, and writes the cookie).
  • Calling use_i18n() without a provided manager raises LookupError naming I18nManager; providing a non-manager value raises TypeError.

Deterministic SSR and hydration parity#

Server rendering and browser hydration agree on the initial locale by construction because both resolve from the exact same inputs using identical deterministic normalization rules:

Browser HTTP Request                     ServerRenderContext (SSR / SSG)
  Cookie: webcompy-locale=en-CA            Registers ServerCookiePort(cookie_header)
        │                                        │
        └───────────────────────────────────────►│ First use_i18n() calls make_manager()
                                                 │  1. initial_locale (if passed) else
                                                 │  2. ServerCookiePort.get("webcompy-locale") -> "en-CA"
                                                 │  3. match_supported("en-CA", {"en-GB", "en-US"})
                                                 │     -> sorted candidates -> "en-GB" (deterministic)
                                                 │  4. Render HTML in "en-GB" + bake use_state payload
                                                 ▼
Browser Boot (app.run()) <────────────────── Shipped HTML + <script id="__webcompy_data__">
  Registers BrowserCookiePort (document.cookie)
        │
        └─► First use_i18n() calls make_manager()
              1. BrowserCookiePort.get("webcompy-locale") -> "en-CA"
              2. Same match_supported("en-CA", {"en-GB", "en-US"}) -> "en-GB"
              3. Signal[str] initialized to "en-GB"
              4. Adopt SSR DOM nodes with zero text or attribute mismatches
  1. Resolution precedence: initial_locale (when passed explicitly to I18nManager) → cookie webcompy-locale → default_locale.
  2. Cookie attributes: Calling controller.set(locale) normalizes locale via supported_locales and persists webcompy-locale=<normalized> through CookiePort.set(...) with max_age=31_536_000 (one year), path="/", and samesite="Lax". Pass persist=False to I18nManager(..., persist=False) to update only the in-memory signal without writing cookies.
  3. Deterministic candidate selection: Normalization compares case-insensitively for an exact supported tag first, then falls back to the language subtag ("de-AT" → "de"). When multiple supported tags share a language subtag (such as {"en-US", "en-GB"}), WebComPy searches candidates in sorted order so "en-CA" deterministically selects "en-GB" regardless of set iteration order on server vs browser. Unsupported cookie values fall back identically to default_locale.
  4. Why Accept-Language and navigator.language are excluded: During SSR, the server cannot see navigator.language; in the browser, PyScript cannot see what Accept-Language header the server received on a cookie-less first visit. Resolving independently on each side would silently pick different locales and cause hydration mismatches. Language-header negotiation belongs in server routing (passing initial_locale=) or redirects before rendering rather than implicit client detection.

Recipes#

1. Nested catalogs, dot paths, and {param} interpolation#

Group keys hierarchically inside per-locale dictionaries and query them by dot-separated path. Keyword arguments passed to t() substitute {param} identifiers:

catalogs = {
    "en": {
        "dashboard": {
            "welcome": "Welcome back, {name} ({role})",
        },
    },
}

manager = I18nManager(catalogs, default_locale="en")
msg_ok = manager.t("dashboard.welcome", name="Alice", role="admin")  # "Welcome back, Alice (admin)"
msg_missing = manager.t("dashboard.welcome", name="Alice")          # "Welcome back, Alice ({role})"

Placeholders with missing keyword arguments stay literal ("{role}") instead of disappearing silently, making missing parameters obvious during development. Non-string scalar leaf values are converted via str().

2. Pluralization with CLDR categories and pipe shorthand#

Plural entries accept either a dictionary keyed by CLDR category names (zero, one, two, few, many, other) or a two-part pipe shorthand for languages with one/other forms:

catalogs = {
    "en": {
        "files": {"one": "{count} file", "other": "{count} files"},
        "alerts": "{count} alert|{count} alerts",
    },
    "ja": {
        "files": {"other": "{count} 件のファイル"},
        "alerts": "{count} 件の通知|{count} 件の通知",
    },
}

manager = I18nManager(catalogs, default_locale="en")
one_file = manager.t("files", count=1)      # "1 file"
three_alerts = manager.t("alerts", count=3) # "3 alerts"

When count= is provided, WebComPy automatically exposes {count} for interpolation alongside any additional keyword parameters. Calling t() on a plural dictionary without count= selects the "other" template.

The built-in plural-rule table covers common locales (en, de, nl, sv, da, no, fi, hu, it, es, el, fr, hi, pt, tr, ja, zh, ko, th, vi, id, ru, uk, pl, cs, sk, ro, he, ar) without external packages. Locales absent from the table warn via warnings.warn(...) and fall back to one/other rules.

3. Opt-in full CLDR plural rules with Babel#

When your application needs full CLDR rules for locales outside the built-in table (or custom rules for existing locales), install the optional babel dependency (uv add babel) and register its adapter once at startup:

from webcompy.i18n._adapters._babel import register_babel_plural_rules

register_babel_plural_rules(["ru", "ar", "pl"])

Omit the argument (register_babel_plural_rules()) to register every locale bundled in Babel. Babel is never imported by webcompy unless you call this helper, keeping default Pyodide bundles lean. To supply a custom selector without Babel, use register_plural_rule(locale, rule, override=True) from webcompy.i18n.

4. Regional overrides and the fallback chain#

Key lookup walks (locale, language_part(locale), fallback_locale) in order and stops at the first catalog containing the requested key:

from webcompy.i18n import I18nManager

catalogs = {
    "en": {"nav": {"home": "Home", "help": "Help Center"}},
    "de": {"nav": {"home": "Startseite"}},
    "de-AT": {"greeting": "Servus, {name}!"},
}

manager = I18nManager(
    catalogs,
    default_locale="en",
    fallback_locale="en",
    supported_locales={"en", "de", "de-AT"},
    initial_locale="de-AT",
)

g = manager.t("greeting", name="Lukas")  # "Servus, Lukas!" (exact "de-AT")
h = manager.t("nav.home")                # "Startseite"     (language "de")
d = manager.t("nav.help")                # "Help Center"    (fallback "en")
m = manager.t("nav.missing")             # "nav.missing"    (raw key when absent everywhere)

Returning the key string when all catalogs miss keeps untranslated strings immediately visible in rendered UI.

5. Locale switcher component and explicit server seeding#

Combine controller.set() in interactive controls with use_computed in rendered text, and use resolve_locale() (or read_locale_from_cookie()) when deriving initial_locale explicitly in custom server setups (such as URL-prefixed locale routes):

from webcompy import use_computed
from webcompy.components import ComponentContext, define_component
from webcompy.elements import html
from webcompy.i18n import I18nManager, resolve_locale, use_i18n


@define_component()
def LanguageSwitcher(context: ComponentContext[None]):
    locale, t, controller = use_i18n()

    return html.DIV(
        {"class": "lang-switcher"},
        html.BUTTON({"@click": lambda _ev: controller.set("en")}, "English"),
        html.BUTTON({"@click": lambda _ev: controller.set("ja")}, "日本語"),
        html.P({}, use_computed(lambda: f"{t('nav.home')} [{locale.value}]")),
    )


def build_manager_for_request(request_headers: dict[str, str], catalogs: dict) -> I18nManager:
    chosen = resolve_locale(
        request_headers,
        supported_locales=["en", "ja"],
        default_locale="en",
    )
    return I18nManager(
        catalogs,
        default_locale="en",
        supported_locales={"en", "ja"},
        initial_locale=chosen,
    )

resolve_locale accepts headers as either a Mapping[str, str] or a sequence of (name, value) tuples, parses webcompy-locale with the same match_supported rules as I18nManager, and ignores Accept-Language.

Behavior notes#

  • Per-app isolation: No module-global locale state exists; multiple WebComPyApp instances or concurrent ServerRenderContext requests keep completely separate active locales inside their DI scopes.
  • No hydration payload bloat: I18nManager holds a standard Signal[str] rather than a transfer slot in <script id="__webcompy_data__">. Because server and browser resolve from the same cookie, the signal re-initializes deterministically during app.run().
  • Implicit supported_locales: Omitting supported_locales defaults it to set(catalogs). Passing a broader set (for instance {"en", "de-AT"} while only "de" has translations) lets users select "de-AT" while falling back to "de" messages.
  • Reactive updates after mount: Calling controller.set(...) from a user click handler updates every active use_computed binding and template {{ t(...) }} node in place and updates document.cookie for future page loads.

Pitfalls#

Late client-side locale mutation breaks parity#

Mutating the locale during mount (or branching on browser-only APIs such as navigator.language or localStorage during setup) breaks deterministic SSR/hydration parity:

from webcompy import use_computed
from webcompy.components import ComponentContext, define_component, on_mounted
from webcompy.elements import html
from webcompy.i18n import use_i18n


@define_component()
def BrokenAutoLocaleBanner(context: ComponentContext[None]):
    locale, t, controller = use_i18n()

    @on_mounted
    def apply_browser_preference():
        controller.set("ja")

    return html.P({}, use_computed(lambda: f"{t('nav.home')} ({locale.value})"))

What goes wrong on a first visit with no webcompy-locale cookie:

  1. Server renders "Home (en)" into the initial HTML because no cookie exists yet and default_locale="en".
  2. Browser hydrates "Home (en)", closes the initial hydration window, and then runs apply_browser_preference() inside @on_mounted — immediately overwriting locale to "ja", visibly flashing the page from English to Japanese and writing a cookie on every visit.
  3. Worse if done inside setup: reading a browser-only source directly inside setup renders "ja" during client adoption against server HTML holding "en", triggering hydration mismatch warnings and forced DOM replacement on boot.

Fix: Keep setup deterministic from cookies (or server-seeded initial_locale). Trigger controller.set(...) only in response to an explicit user action (@click / @change), or negotiate redirects server-side before HTML rendering.

Providing a pre-built instance instead of a factory#

Calling app.provide(I18N_KEY, I18nManager(catalogs, default_locale="en")) constructs the manager at import time outside any RenderContext (where no CookiePort exists) and shares one signal across every concurrent SSR request. Always pass the callable factory (app.provide(I18N_KEY, make_i18n_manager)).

Evaluating t() directly in html.* children without use_computed#

Writing html.P({}, t("nav.home")) evaluates t("nav.home") eagerly once when creating the VDOM node; calling controller.set("ja") later will not update that text node. Wrap reactive element text or attributes in use_computed(lambda: t("nav.home")), or use render_template("{{ t('nav.home') }}", {"t": t}).

Missing "other" key or duplicate rule registration#

Every plural dict should define an "other" fallback category; if both the selected category and "other" are missing, t() falls back to the raw key string. Calling register_plural_rule("en", fn) without override=True for an already-registered language raises ValueError.

Next steps#