🌍 Internationalization (Translations)
Translations are used to internationalize an application and display content in different
languages. In Lila, translations are stored in the app/locales
directory
and
can be dynamically loaded into the application.
🛤️ Forcing Default Language in Routes
The render
method accepts a lang_default
parameter to force a
specific language for the rendered template:
app.routes.py
# Force Spanish language
@router.route(path="/es", methods=["GET"])
async def home(request: Request):
response = render(
request=request,
template="index",
lang_default="es" # Forces Spanish translations
)
return response
# Force English language
@router.route(path="/en", methods=["GET"])
async def home(request: Request):
response = render(
request=request,
template="index",
lang_default="en" # Forces English translations
)
return response
📄 Translation Files
To load a locale file, use the Translate
class from
lila.core.translate.
You can access translations using:
Translate.get_translations- returns a dictionary with all translationsTranslate.t- returns a specific translation (returns original text if not found)
Example translation file (app/locales/translations.json):
app/locales/translations.json
{
"Send": {
"es": "Enviar",
"en": "Send"
},
"Cancel": {
"es": "Cancelar",
"en": "Cancel"
},
"Accept": {
"es": "Aceptar",
"en": "Accept"
},
"Email": {
"es": "Email",
"en": "Email"
},
"Name": {
"es": "Nombre",
"en": "Name"
},
"Back": {
"es": "Volver",
"en": "Back"
},
"Hi": {
"es": "Hola",
"en": "Hi"
}
}
🔧 Using Translations
Get a specific translation:
example.py
from lila.core.translate import Translate
msg_error_login = Translate.t(
key="Incorrect email or password",
request=request,
file_name="guest"
)
Get all translations from a file:
example.py
from lila.core.translate import Translate
all_translations = Translate.get_translations(
request=request,
file_name="guest"
)
index.html
{{ translate["Send"]}}
{{ translate['also_left_in'] }}
{{ translate['and_in'] }}
{{ translate['examples_of_how_to_use'] }} {{
translate['routes_queries_crud'] }} ({{
translate['crud_with_30_lines'] }}, {{
translate['with_middlewares_validations'] }}, {{
translate['and_more'] }}!)