🎨 Template Rendering (Jinja2)
In Lila, you can use Jinja2 to render HTML with server data
Jinja2 is the default for rendering HTML templates. You can pass
data like translations, values, lists, or dictionaries using the
context
parameter.
Basic Usage in Routes
from lila.core.templates import render
from lila.core.responses import Response
from lila.core.routing import Router
from lila.core.request import Request
router = Router()
@router.get("/")
async def home(request: Request):
"""Home page"""
context = {
"title": "Lila Framework",
"message": "Hello from Lila!"
}
response = render(
request,
"index.html", # HTML template name in resources/templates/html/
context=context
)
# Renders the 'index' template
return response
routes=router.get_routes()
The
render
Function
The
render
function is located in
lila.core.templates:
def render(request: Request, template: str, context: dict = None, files_translate: list[str] = None, lang_default: str = None):
Parameter Description
-
request:
The
Requestobject. -
template (str):
Template name (without the
.htmlextension). -
context (dict):
Data to pass to the template (dictionaries, lists, etc.).
-
files_translate (list):
List of additional translation files.
-
lang_default (str):
Forced default language (ideal for SEO in routes like
/es,/en, etc.).
In Lila, you can also use
translate
to pass translations to Jinja2, and parameters like
title
or
version
(ideal for structuring APIs: "v1", "v2").
Base Context Injection
All optimization features work thanks to the base context automatically injected into Jinja2 templates:
def get_base_context(request, files_translate=[], lang_default=None):
context = {
"title": TITLE_PROJECT,
"version": VERSION_PROJECT,
"lang": lang_default if lang_default else lang(request),
"translate": t("translations", request, lang_default=lang_default),
"description": DESCRIPTION_DEFAULT,
"keywords": KEYWORDS_DEFAULT,
"author": AUTHOR_DEFAULT,
}
for file_name in files_translate:
context["translate"].update(
t(file_name, request, lang_default=lang_default)
)
return context
Jinja2 Helpers
Lila provides several helpers to make your templates more powerful:
-
hot_reload():
Injects Vite's Hot Module Replacement (HMR) scripts. Only active when DEBUG=True. Place it in the
<head>of your main layout. -
vite_assets():
In production, it injects the compiled scripts and styles from the manifest. In development, it injects the main entry point (
main.jsx). -
react(component_name, props):
Creates a mount point for a React Island.
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
{{ hot_reload() | safe }}
</head>
<body>
<h1>Welcome</h1>
{{ vite_assets() | safe }}
</body>
</html>