Localization & Validation Translations (v2.0)
In Lila v2.0, the localization system was rebuilt to be lightweight: locale files are loaded once and cached in memory, the language is resolved in O(1), and the main focus is Pydantic v2 validation error localization.
Pydantic v2 Error Localization
When request bodies, forms, or query parameters fail Pydantic validation, Lila automatically translates the error codes into clear, human-readable messages in the user's preferred language (Spanish es, English en, Portuguese pt):
from lila.core.routing import Router
from lila.core.request import Request
from pydantic import BaseModel, EmailStr, Field
router = Router()
class UserSchema(BaseModel):
name: str = Field(..., min_length=3)
email: EmailStr
@router.post("/users", model=UserSchema)
async def create_user(request: Request, data: UserSchema):
return {"success": True}
# If a client sends {"name": "A", "email": "invalid"}, Lila returns HTTP 422:
# In Spanish: "El campo 'name' debe tener al menos 3 caracteres."
# In English: "Field 'name' must be at least 3 characters long."
O(1) Language Detection
Language resolution order:
- Query param:
?lang=es - Cookie:
lang=es - Header:
Accept-Language: es-ES,es;q=0.9(q-values and regions honored) - Fallback:
LANG_DEFAULTin.env(framework default:"es")
en, es, pt and
zh. The resolved code is exposed as lang in templates and via
Translate.lang(request).
Forcing Language Manually (Fallback)
If you still need to force a specific language manually without using localized route prefixes, the render method also accepts an optional lang_default parameter:
@router.get("/custom-es")
async def custom_home(request: Request):
response = render(
request=request,
template="index",
lang_default="es" # Manually forces Spanish translations
)
return response
Translation Files
Use the Translate
class from
lila.core.translate:
Translate.get_dict(lang=None)- returns the merged dictionary for a language (built-ins + project overrides)Translate.t(key, lang=None, request=None, default=None, file_name=None)- returns one translation; falls back todefault, then to the key itselfTranslate.lang(request)/Translate.set_lang(request, response, lang)- resolve or persist the language
Locale files are flat JSON and live at
app/locales/{lang}.json (one file per language). Keys are
merged over the built-in dictionary:
{
"login": "Welcome Back",
"send": "Send",
"cancel": "Cancel",
"accept": "Accept",
"email": "Email",
"name": "Name",
"back": "Back",
"hi": "Hi"
}
The equivalent app/locales/es.json would contain
{"send": "Enviar", "cancel": "Cancelar", ...}. Nested
{"Send": {"es": ..., "en": ...}} maps are not supported.
Using Translations
Get a specific translation:
from lila.core.translate import Translate
# Resolve the language from the request (query param -> cookie -> header -> LANG_DEFAULT)
msg_error_login = Translate.t(
key="incorrect_email_or_password",
request=request,
default="Incorrect email or password",
)
# Force a language / provide a fallback
msg_es = Translate.t("login", lang="es", default="Iniciar sesión")
# file_name is a deprecated v1 compatibility argument: it looks up
# "file_name.key" in the same flat dictionary, then falls back to key/default.
legacy = Translate.t("title", file_name="guest", default="Welcome")
Helpers and Performance
Lila includes helpers to manage the application state and keep locale lookups in memory.
Setting the Language
Translate.set_lang(request, response, lang) writes a
lang cookie (not a session, and not encrypted — it only holds the language
code) that Translate.lang() reads on the next request.
Option A: Dynamic POST Route (e.g. for fetch/AJAX)
from lila.core.translate import Translate
@router.post("/set-language")
async def change_lang(request: Request):
data = await request.json()
new_lang = str(data.get("lang", "en"))[:2].lower()
response = JSONResponse({"success": True, "lang": new_lang})
Translate.set_lang(request, response, new_lang) # sync helper
return response
Option B: Per-request switch with the query parameter
Translate.lang(request) reads ?lang=code first, so appending
?lang=es to a URL renders that one request in Spanish. It does not persist
the preference — call Translate.set_lang() (or write the cookie yourself) if
you want it to survive navigation.
<!-- Renders this page in Spanish for this request -->
<a href="?lang=es">🇪🇸 Español</a>
<a href="?lang=en">🇺🇸 English</a>
<!-- To persist the choice, call the POST /set-language route shown above
with fetch(), or call Translate.set_lang() in your own route. -->
Translating Pydantic Errors
If you use Pydantic models for validation, you can translate the error messages into Spanish automatically.
try:
user = UserModel(**data)
except ValidationError as e:
# Translates the first error found
err_msg = Translate.translate_pydantic_error(e.errors()[0], target_lang="es")
return JSONResponse({"error": err_msg}, status_code=400)
Performance note: Translate.get_dict() loads each language
once and keeps the merged dictionary in memory; Translate.lang() resolves the
language from the request without any disk I/O. Pydantic messages come from in-memory
catalogs.
Usage in Templates
Translations are available as translate (a dict) and t() (a function):
{{ translate["send"] }}
<!-- With a fallback (missing keys render the default) -->
{{ translate["missing_key"] | default('Fallback label') }}
<!-- Function form -->
{{ t('login', default='Welcome Back') }}
<!-- With variables -->
{{ translate["hi"] }} {{ user.name }}