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

Render function

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.

resources/html/authenticated/dashboard.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 %}
app/routes/dashboard.py
@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
    )

Custom layouts

resources/html/layouts/app.jinja
<!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:

Template

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

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:

Base Context

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:

Usage Example
<!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.

DataTable
{# 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
{{ 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.

Python
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"}
resources/html/signup.jinja
{{ form(Signup, action="/api/signup", submit="register", snackbar=True, columns=2) }}

UI components, pagination and images

Jinja
{{ 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.

Route (Python)

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})
Template (Jinja2)

<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:

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: