Added template API documentation.

2026-02-27 10:05:05 -05:00
parent 4c6c3f2658
commit b26ca8b75f
2 changed files with 26 additions and 14 deletions
+25 -13
@@ -168,9 +168,11 @@ url = ctx.routes.url_for("/list")
This uses the `public_base_url` from config. If not set, it falls back to `owncast.url`. Set `public_base_url` if Owlbot is hosted on a different domain than your Owncast instance.
## Templates with Jinja2
## Templates
For HTML pages, [Jinja2](https://jinja.palletsprojects.com/) templates can be used. Jinja2 is already a dependency of Owlbot, so no extra install is needed. Modules that use templates should be structured as a package so the template files can be bundled alongside the code:
Every module has access to a Jinja2 template environment via `ctx.templates`. Templates are loaded from the module's `templates/` directory first, then from Owlbot's core templates (which includes a Bootstrap `base.html`). Autoescape is enabled by default.
Modules that use templates should be structured as a package so the template files can be bundled alongside the code:
```
modules/my_module/
@@ -181,26 +183,36 @@ modules/my_module/
```python
# modules/my_module/__init__.py
from pathlib import Path
import jinja2
from aiohttp import web
from owlbot.api import RouteContext, on_route
_template_dir = Path(__file__).resolve().parent / "templates"
_jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(_template_dir),
autoescape=True,
)
@on_route("/list")
async def list_page(ctx: RouteContext) -> web.Response:
items = ["apples", "oranges", "bananas"]
template = _jinja_env.get_template("list.html")
html = template.render(items=items)
html = ctx.templates.render("list.html", items=items)
return web.Response(text=html, content_type="text/html")
```
Templates can extend Owlbot's core `base.html` to inherit a Bootstrap layout:
```html
{# modules/my_module/templates/list.html #}
{% extends "base.html" %}
{% block title %}My Items{% endblock %}
{% block content %}
<h1>Items</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endblock %}
```
The `base.html` template provides four blocks: `title`, `head`, `content`, and `scripts`.
For advanced use (custom filters, globals, etc.), access the underlying Jinja2 `Environment` via `ctx.templates.env`.
## Request Access
`ctx.request` is a standard `aiohttp.web.Request`. Some common patterns:
+1 -1
@@ -248,4 +248,4 @@ async def quotes_page(ctx: RouteContext) -> web.Response:
)
```
For more complex HTML, Jinja2 templates can be used from a package module's `templates/` directory. See [HTTP Routes](Modules-Routes) for that pattern.
For more complex HTML, use `ctx.templates.render()` with Jinja2 templates from a package module's `templates/` directory. Templates can extend Owlbot's built-in `base.html` for a Bootstrap layout. See [HTTP Routes](Modules-Routes) for details.