Skip to content

Internationalization (i18n)

P8s provides Django-style internationalization support for translating your application.

Quick Start

from p8s.i18n import gettext as _, activate

# Activate a language
activate("it")

# Translate strings
message = _("Welcome to our store")

Configuration

from p8s.i18n import configure

configure(locale_dir="locale/")

Translation Functions

Basic Translation

from p8s.i18n import gettext as _

welcome = _("Hello, World!")

Plural Forms

from p8s.i18n import ngettext

message = ngettext("1 item", "{n} items", count)

Context-Based Translation

from p8s.i18n import pgettext

# Different translations for same word
month_may = pgettext("month", "May")
verb_may = pgettext("verb", "May")

Lazy Translation

from p8s.i18n import gettext_lazy as _

class Product:
    verbose_name = _("Product")  # Translated on access

Locale Middleware

Automatically detect language from requests:

from p8s.i18n.middleware import LocaleMiddleware

app.add_middleware(
    LocaleMiddleware,
    default_language="en",
    supported_languages=["en", "it", "fr", "de"],
)

The middleware detects language from: 1. URL prefix (if enabled): /it/products/ 2. Cookie 3. Accept-Language header

Translation Files

Structure your locale directory:

locale/
├── it/
│   └── LC_MESSAGES/
│       └── messages.po
├── fr/
│   └── LC_MESSAGES/
│       └── messages.po