An open API service indexing awesome lists of open source software.

https://github.com/flokapi/hotmix

Add htmx to your FastAPI app
https://github.com/flokapi/hotmix

fastapi htmx python

Last synced: 4 months ago
JSON representation

Add htmx to your FastAPI app

Awesome Lists containing this project

README

          

# About

HotMix allows you to conveniently add htmx to your FastAPI app.

# Getting Started

Install the packages

```
pip install uvicorn fastapi jinja2 hotmix
```

Create a tempate folder and add a template.

```
main.py
templates/
index.html
```

Content of `index.html`

```html




Simple Page


HotMix Hello World


Parameter from the API: {{ param }}


You are accessing the path: {{ request.url.path }}


```

Content of `main.py`

```python
from fastapi import FastAPI, Request
import hotmix as hm

app = FastAPI()
hm.init("templates")

@app.get("/")
@hm.htmx("index")
async def main(request: Request):
return {"param": 37}
```

# How it works

Initialize hotmix while setting the templates folder path

```python
import hotmix as hm

hm.init("templates")
```

For each of the routes which should return some htmx content, add a decorator specifying the name of the template file, without the `.html` extension.

```python
@app.get("/")
@hm.htmx("index")
async def main(request: Request):
return {"param": 37}
```

Instead of returning the dictionary as JSON data, it will pass the dictionary to the jinja2 template engine, which will return the `.html` with the desired parameters.

HotMix can handle two kinds of parameters:

- Explicit paramters: returned in the request answer dictionary. They are accessed by giving their names: `{{ param }}`.
- Request parameters, accessed through the `request` keyword. For example `{{ request.url.path }}`.