Templating with Jinja2

Xyra uses the powerful Jinja2 templating engine to render dynamic HTML. This allows you to embed expressions and logic directly into your HTML files.

Configuration

To enable templating, specify the templates_directory when you create the App instance. A common convention is to name this folder "templates".

Python
from xyra import App

# Xyra will now look for templates in a "templates" directory
app = App(templates_directory="templates")

Rendering Templates

Use the res.render() method to render a template. The first argument is the template filename, and subsequent keyword arguments are passed to the template as context variables.

Python
from xyra import App, Request, Response

app = App(templates_directory="templates")

@app.get("/")
def home(req: Request, res: Response):
    # This will render "templates/index.html"
    res.render("index.html", title="Home Page", message="Welcome to Xyra!")

Example Template

Here’s an example of a Jinja2 template file located at templates/index.html:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ message }}</h1>
    <p>This is a dynamic page rendered by Xyra.</p>
</body>
</html>

When a user visits the / route, Xyra will render this template, replacing {{ title }} and {{ message }} with the values provided in the res.render() call.