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.routing import Router
from lila.core.request import Request
router = Router()
@router.get("/")
async def home(request: Request):
"""Home page: the template only contains its HTML."""
return render(
request,
"index", # resources/html/index.jinja
{"message": "Hello from Lila!"},
title="Lila Framework", # <title>, og:title
description="Full-stack Python",
)
routes = router.get_routes()
Automatic layout: pages are just HTML
A page template does not need {% extends %}, {% block title %}
or {% block content %}. render() wraps it in the default layout
(lila/base.jinja, change it with set_default_layout()) and builds the
whole <head> from its keyword arguments, @seo/SEO_CONFIG and
.env. The wrapped template is compiled once and cached by Jinja.
<main class="max-w-7xl mx-auto px-4 py-8 space-y-6">
<h1 class="text-3xl font-black">{{ translate['welcome'] }}, {{ user.name }}!</h1>
{% include "components/stats.jinja" %} {# includes are never wrapped #}
</main>
{# Optional: extra tags for <head> / end of <body> are moved to the layout #}
{% block head %}<meta name="theme-color" content="#1a73e8" data-lila-head>{% endblock %}
@router.get("/dashboard", auth=True)
async def dashboard(request: Request):
return render(
request,
"authenticated/dashboard",
{"user": request.state.user},
title="dashboard", # a translation key is translated -> "Panel de Control - My App"
description="Your panel",
robots="noindex",
canonical=True, # True = APP_URL + current path
image="img/og.png", # og:image / twitter:image (absolute URL generated)
jsonld={"@context": "https://schema.org", "@type": "WebPage", "name": "Dashboard"},
meta={"theme-color": "#1a73e8", "og:locale": "es_AR"},
styles=["css/dashboard.css"],
scripts=["js/chart.js"], # loaded in <head>, before the page's inline scripts
)
- Precedence:
.envdefaults <SEO_CONFIG/@seo<context<render()keywords. <title>usesTITLE_TEMPLATEfrom.env(default"{title} - {project}", project =TITLE_PROJECT).layout=Noneuses the default layout,layout="admin/layout.jinja"another one andlayout=Falserenders the template as a fragment.- Templates that already use
{% extends %}or contain<html>/<!DOCTYPE>are rendered unchanged, so 2.0.0 templates keep working. - Tags produced by
styles,scriptsandjsonldcarrydata-lila-head: the SPA router swaps them (and<html lang>) on every navigation. Adddata-lila-headto your own page-specific head tags. head="..."is inserted as raw HTML (trusted developer input); every other value is escaped. JSON-LD is serialized so it cannot close its<script>.- Page scripts run again on every SPA visit: declare globals with
var/function(not top-levellet/const) and call init code directly instead of waiting forDOMContentLoaded.
Custom layouts
<!DOCTYPE html>
<html lang="{{ lang }}" data-theme="light">
<head>
{% include "lila/head.jinja" %} {# title, meta, OG, JSON-LD, icon, Tailwind, CSRF meta #}
{% block head %}{% endblock %}
</head>
<body data-layout="app" class="{{ page_meta.body_class or 'min-h-screen bg-bg-body dark:bg-bg-body-dark' }}">
<nav data-persist="true" id="main-nav">...</nav>
<div data-lila-outlet>{% block content %}{% endblock %}</div>
<script src="{{ public('js/lila-client.js') }}"></script>
{% block scripts %}{% endblock %}
</body>
</html>
Use it per page with render(..., layout="layouts/app.jinja") or globally with
set_default_layout("layouts/app.jinja").
The render Function
The
render
function is located in
lila.core.templates:
def render(
request: Request,
template_name: str | None = None,
context: dict | None = None,
extension: str = "jinja",
csrf: bool = False,
status_code: int = 200,
template: str | None = None, # alias for template_name
layout: str | bool | None = None, # None = default layout, False = no layout
headers: dict | None = None,
lang_default: str | None = None,
files_translate: list | None = None, # accepted for v1 compatibility
*,
title=None, description=None, keywords=None, author=None,
image=None, icon=None, canonical=None, robots=None, og_type=None,
jsonld=None, meta=None, styles=None, scripts=None, head=None, body_class=None,
) -> HTMLResponse: ...
# render_markdown is also available:
def render_markdown(request, markdown_path, context=None, css_files=None, js_files=None): ...
Parameter Description
-
request:
The
Requestobject. -
template_name (str):
Template name.
.jinjais preferred, but legacy.htmlnames are accepted ("index.html"also findsindex.jinja). With no extension,.jinjais used. -
context (dict):
Data to pass to the template (dictionaries, lists, etc.). It is merged over the base context.
-
csrf (bool):
Accepted for readability. A CSRF token, the signed
_csrfcookie andcsrf_inputare produced on every render. -
status_code / headers / layout:
Response status (default 200), extra response headers and the layout:
None= default layout, a template name = that layout,False= render the template as a fragment. -
title / description / keywords / author:
SEO texts. A value that is a translation key (
"dashboard") is translated to the request language. -
image / icon / canonical / robots / og_type:
Open Graph image (relative paths become absolute), favicon (default
favicon.ico), canonical URL (True= current URL), robots directive andog:type(defaultwebsite). -
jsonld / meta / styles / scripts / head / body_class:
JSON-LD dict or list, extra
<meta>(og:*keys useproperty), stylesheet and script URLs (relative paths go throughpublic()), raw trusted HTML for<head>and the<body>class of the default layout. -
files_translate (list):
Deprecated v1 parameter. It is accepted but ignored: v2 locale files are flat JSON merged by language (
app/locales/{lang}.json). -
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, lang_default=None, files_translate=None):
# Values are resolved from .env / ConfigLoader and the request.
return {
"request": request,
"title": ENV_CONFIG.get("TITLE_PROJECT", "Lila Application"),
"description": ENV_CONFIG.get("DESCRIPTION_PROJECT", ...),
"keywords": ENV_CONFIG.get("KEYWORDS_DEFAULT", ""),
"author": ENV_CONFIG.get("AUTHOR_DEFAULT", ""),
"version": ENV_CONFIG.get("VERSION_PROJECT", "2.0.0"),
"lang": current_lang,
"translate": Translate.get_dict(current_lang),
"t": lambda key, default=None: Translate.t(key, lang=current_lang, default=default),
"app_url": app_url,
"debug": is_debug(),
"debug_html": is_debug(),
"layout": DEFAULT_LAYOUT, # "lila/base.jinja"
"csrf_token": "",
}
# render() then adds: csrf_token, csrf_input, "seo" and "page_meta" (the resolved
# title/full_title/description/image/jsonld/styles/scripts used by lila/head.jinja).
Jinja2 Helpers
Lila registers these helpers as Jinja2 globals:
-
public(path):
Resolves an asset under
public/to a URL, applies thelila optimizemanifest (for exampleapp.js→app.min.js,photo.png→photo.webp) and appends?v=<mtime>for cache busting. WhenAPP_URLis set and DEBUG is off, the URL is absolute. -
asset(path):
Returns a ready-to-use tag: a
<link rel="stylesheet">for.css, a<script src="...">for.js, or the resolved URL otherwise. It does not load fonts or other files implicitly. -
t(key, default=None) / translate:
Current-language translation function and dictionary (
translate['login']). -
oauth_buttons():
Renders the Google/GitHub/Discord buttons for the configured providers. Use
{{ oauth_buttons() | safe }}.
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<!-- Load Tailwind CSS v4 browser runtime and theme variables -->
{{ asset('js/tailwind.js') | safe }}
</head>
<body>
<h1>Welcome to Lila!</h1>
<!-- Load javascript -->
<script src="{{ public('js/main.js') }}"></script>
</body>
</html>
Components from Jinja: datatable() and carousel()
Both helpers generate a unique id automatically, escape every value and are initialized by
lila-client.js on the first load and after each SPA navigation.
{# rows embedded in the page (password/token/hash keys are never embedded) #}
{{ datatable(users, ["id", "name", ("email", "E-mail")], rows_per_page=10, edit="onEditUser", delete="onDeleteUser") }}
{# or loaded with Http() — data_key reads {"data": [...]} style responses #}
{{ datatable(url="/api/users", columns=["id", "name"], data_key="data", id="users-table") }}
<script>
function onEditUser(event, item) { location.href = "/users/" + item.id; }
function onDeleteUser(event, item) { /* Http(`/api/users/${item.id}`, "DELETE") */ }
</script>
Options: id, rows_per_page, search, pagination,
summary_fields (mobile card summary), id_key, breakpoint, exclude,
css_class. Model instances and Pydantic objects are converted automatically. The instance is
available as document.getElementById(id)._lila_datatable and a lila:datatable-ready event is fired.
{{ carousel([
{"image": "img/slide-1.webp", "title": "Fast", "text": "Starlette + Pydantic v2", "href": "/docs"},
{"image": "img/slide-2.webp", "title": "Simple"},
], autoplay=5000) }}
{# several cards per view #}
{{ carousel(products_html, item_class="basis-full sm:basis-1/2 lg:basis-1/3 pr-4", height="h-80", indicators=False) }}
Slides can be dicts (image, alt, title, text,
href), plain text or Markup (trusted HTML). Options: autoplay (ms, 0 = off),
loop, arrows, indicators, item_class, height,
css_class, id. Touch swipe uses native scroll-snap, arrow keys work when focused, autoplay
pauses on hover/focus/hidden tabs and respects prefers-reduced-motion. JS API:
el._lila_carousel.next()/prev()/go(i)/stop().
Forms from Pydantic models
{{ form(Model, ...) }} builds a data-lila-form whose inputs mirror the validation rules, so the browser and the server always agree.
from typing import Literal, Optional
from pydantic import BaseModel, EmailStr, Field
class Signup(BaseModel):
name: str = Field(min_length=2, max_length=50, title="Full name")
email: EmailStr
age: Optional[int] = Field(default=None, ge=18, le=120)
password: str = Field(min_length=8)
password_2: str = Field(json_schema_extra={"ui": {"match": "password", "label": "Repeat password"}})
plan: Literal["free", "pro"] = "free"
bio: Optional[str] = Field(default=None, json_schema_extra={"ui": {"widget": "textarea"}})
terms: bool = False
@router.get("/signup")
async def signup_page(request: Request):
return render(request, "signup", {"Signup": Signup}, title="register")
@router.post("/api/signup", model=Signup, csrf=True)
async def signup(request: Request, data: Signup):
...
return {"success": True, "message": "Welcome!", "redirect": "/dashboard"}
{{ form(Signup, action="/api/signup", submit="register", snackbar=True, columns=2) }}
EmailStr→type="email",min_length/max_length→minlength/maxlength,ge/le→min/max,int/float→ number,Literal/Enum→ select,bool→ checkbox, dates → date inputs, password fields →type="password".json_schema_extra={"ui": {...}}:widget(textarea/hidden),label,help,placeholder,type,match.- Options:
values,errors,fields/exclude,method,snackbar,toast,redirect,reset,target,columns,attrs. The CSRF field is included and 422 errors appear under each field.
UI components, pagination and images
{{ ui.input("email", "email", type="email", required=True, error=errors.email) }}
{{ ui.select("country", {"ar": "Argentina", "es": "España"}, "Country", value=user.country) }}
{{ ui.textarea("bio", "Bio", rows=3) }}
{{ ui.checkbox("newsletter", "Send me news", checked=True) }}
{{ ui.button("save", type="submit") }} {{ ui.link("Cancel", "/profile", variant="secondary") }}
{{ ui.alert("Saved!", type="success", dismissible=True) }} {{ ui.badge("Active", color="green") }}
{{ ui.modal("confirm", "Delete item?", "This cannot be undone.") }} {# open with data-modal-target="#confirm" #}
{{ pagination(page) }} {# page = await Model.paginate_async(...) #}
{{ image("img/hero.jpg", alt="Our team", widths=[480, 960, 1440], sizes="(min-width: 768px) 50vw, 100vw") }}
{% if can("posts.edit") %}...{% endif %} {% if has_role("admin") %}...{% endif %}
Labels and texts that are translation keys are translated. image() creates WebP variants once in public/img/_r/ with Pillow (pip install "lila-framework[images]"), never upscales, writes width/height (no layout shift) and lazy-loads. Without Pillow it uses the original file.
Note: the SEO data used by the layout is available as page_meta; page is free for your own data (pagination).
CSRF Protection in Templates
Every render() generates a signed CSRF token, sets the _csrf cookie and injects csrf_token, csrf_input into the template context. Passing csrf=True is accepted for readability; it does not change the token generation.
-
render(request, template, csrf=True):
Produces
csrf_tokenin the context and the signed_csrfcookie on the response. -
csrf_input:
Ready-made hidden input:
<input type="hidden" name="_csrf" id="csrf" value="TOKEN" />. Use it with the| safefilter. The base context also includes therequestobject, so templates can access request data. -
meta tag:
The bundled
lila/tailwind.jinjapartial prints<meta name="csrf-token" content="{{ csrf_token }}">, which the clientHttp()helper reads automatically.
from lila.core.templates import render
from lila.core.middleware import csrf
@router.get('/contact')
async def contact_page(request: Request):
return render(request, 'contact', csrf=True)
@router.post('/contact')
@csrf
async def contact_submit(request: Request):
return JSONResponse({"success": True})
<form method="POST" action="/contact">
{{ csrf_input | safe }}
<input type="text" name="name" />
<button type="submit">Send</button>
</form>
The Http() helper in public/js/lila-client.js reads <meta name="csrf-token"> (or the #csrf input) and sends the value as the X-CSRF-Token header on every fetch. No additional client-side code is needed.
Lila CSS Utility Components
The bundled Tailwind setup includes a set of pre-configured utility classes that support dark mode natively. They are loaded by the layout's Tailwind Play CDN script (development) or by your precompiled CSS in production:
-
.cardA beautiful, fully-responsive Material Design container card with light/dark border coloring, rounded-2xl padding, and smooth transition shadows.
-
.text-lilaA premium, high-impact gradient title class styling using Lila's custom primary/secondary colors. Ideal for hero headers!
-
.input-lilaA state-of-the-art interactive input class with elegant borders, dynamic focus ring effects, light/dark text support, and a smooth cursor placeholder transition.
-
.link-lilaA gorgeous navigational anchor link styling with custom primary color transitions and sleek animated underlines.
-
.btn-primary/.btn-secondary/.btn-outlinePre-configured button styles featuring smooth translate-y hover elevations, beautiful color variations, and integrated loading/icon layout alignment.
Performance Notes
Templates are rendered by a single Jinja2 environment (auto-reload only in debug). Under
lila dev, Jinja auto-reload is enabled and the SSE watcher reloads the browser
and clears the locale/asset caches after template, locale or static edits. Some honest
details:
- Request state:
@seometadata is stored onrequest.state.seoand merged into the context, so a handler does not recompute it. - Translation caching: locale dictionaries are loaded once per language and kept
in memory (
SafeTranslationDict); the dev watcher clears that cache on edit. - No HTML minification: Lila does not minify rendered HTML. Use
lila optimizefor JS/CSS/images and thegzip=TrueApp option (or your reverse proxy) for transport compression.