Created
February 20, 2023 21:58
-
-
Save angelospanag/11523e108d1cf3dd42e9d0951f8337cc to your computer and use it in GitHub Desktop.
HTMX trigger examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div> | |
<ul> | |
{%for element in elements %} | |
<li>{{element}}</li> | |
{% endfor %} | |
</ul> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Books</title> | |
<script src="{{ url_for('static', path='js/htmx.min.js') }}"></script> | |
</head> | |
<body> | |
<label for="books">Please choose one or more books</label> | |
<select | |
hx-get="/books" | |
hx-trigger="change" | |
hx-swap="beforeend" | |
hx-include="#books" | |
hx-target="#response-area" | |
id="books" | |
name="books" | |
multiple | |
size="4" | |
> | |
<option value="BOOK1">BOOK1</option> | |
<option value="BOOK2">BOOK2</option> | |
<option value="BOOK3" disabled>BOOK3</option> | |
<option value="BOOK4">BOOK4</option> | |
<option value="BOOK5">BOOK5</option> | |
<option value="BOOK6">BOOK6</option> | |
</select> | |
<h2 | |
hx-get="/books" | |
hx-trigger="click" | |
hx-swap="beforeend" | |
hx-include="#books" | |
hx-target="#response-area" | |
> | |
Also click me to load | |
</h2> | |
<div id="response-area"></div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI, Query, Request | |
from fastapi.responses import HTMLResponse | |
from fastapi.staticfiles import StaticFiles | |
from fastapi.templating import Jinja2Templates | |
app = FastAPI() | |
app.mount("/static", StaticFiles(directory="static"), name="static") | |
templates = Jinja2Templates(directory="templates") | |
@app.get("/", response_class=HTMLResponse) | |
async def read_item(request: Request): | |
return templates.TemplateResponse("index.html", {"request": request}) | |
@app.get("/books", response_class=HTMLResponse) | |
async def get_elements(request: Request, books: list[str] | None = Query(default=None)): | |
if not books: | |
books = [] | |
return templates.TemplateResponse("books.html", {"request": request, "elements": books}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment