Views

Views — sometimes called templates — are used to render, as HTML, the user interface of a web application. They define how data is presented to the user and can include HTML, CSS, and JavaScript.

Expanse relies on the Jinja2 templating engine to render views. This means you can use all the features provided by Jinja2, such as template inheritance, macros, filters, and more out of the box.

This section will guide you through the basics of using views in Expanse and the specifics of its integration with Jinja2.

Creating and rendering views

To create a view, you need to create a new file with the .jinja2 extension in the views directory of your project.

For example, you can create a home.jinja2 file with the following content:

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
  </head>
  <body>
  <h1>Welcome to Expanse!</h1>
  <p>This is the home page.</p>
  </body>
</html>

To render this view from a route handler, you can use the view response helper provided by Expanse:

from expanse.core.http.helpers import view
from expanse.core.http.response.response import Response


async def home_controller() -> Response:
    return view("home.jinja2")

When the home_controller is called, it will render the home.jinja2 view and return it as an HTML response.

Passing data to views

You can pass data to views by providing a dictionary of variables to the view helper. These variables will be available in the view for rendering.

For example, you can modify the home_controller to pass a username variable to the view:

from expanse.core.http.helpers import view
from expanse.core.http.response.response import Response


async def home_controller() -> Response:
    return view(
        "home.jinja2",
        data={"username": "JohnDoe"}
    )

Then, you can use the username variable in the home.jinja2 view:

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
  </head>
  <body>
  <h1>Welcome to Expanse, {{ username }}!</h1>
  <p>This is the home page.</p>
  </body>
</html>