|
| 1 | +from fasthtml.common import * |
| 2 | + |
| 3 | +app, rt = fast_app() |
| 4 | + |
| 5 | +# This represents the data we are rendering |
| 6 | +# The data could original from a database, or any other datastore |
| 7 | +@dataclass |
| 8 | +class Contact: |
| 9 | + # Data points |
| 10 | + id: int |
| 11 | + name: str |
| 12 | + email: str |
| 13 | + status: str |
| 14 | + |
| 15 | + def __ft__(self): |
| 16 | + # __ft__ method is used by FastHTML to render an item in the UI |
| 17 | + # By defining this, a `Contact` will show up as a table row automatically |
| 18 | + return Tr( |
| 19 | + *map(Td, (self.name, self.email, self.status)), |
| 20 | + Td(Button('Delete', |
| 21 | + hx_delete=delete.to(id=self.id).lstrip('/'), |
| 22 | + # Give a confirmation prompt before deleting |
| 23 | + hx_confirm="Are you sure?", |
| 24 | + # Target the closest row (The one you clicked on) |
| 25 | + hx_target="closest tr", |
| 26 | + # Swap out the row with nothing (removes the row) |
| 27 | + hx_swap="outerHTML"))) |
| 28 | + |
| 29 | +# Sample data |
| 30 | +# Often this would come from a database |
| 31 | +contacts = [{ 'id': 1, 'name': "Bob Deer", 'email': "[email protected]", 'status': "Active" }, |
| 32 | + { 'id': 2, 'name': "Jon Doe", 'email': "[email protected]", 'status': "Inactive"}, |
| 33 | + { 'id': 3, 'name': "Jane Smith", 'email': "[email protected]", 'status': "Active" }] |
| 34 | + |
| 35 | +@rt |
| 36 | +def index(sess): |
| 37 | + # Save a copy of contacts in your session |
| 38 | + # This is the demo doesn't conflict with other users |
| 39 | + sess['contacts'] = contacts |
| 40 | + # Create initial table |
| 41 | + return Table( |
| 42 | + Thead(Tr(*map(Th, ["Name", "Email", "Status", ""]))), |
| 43 | + # A `Contact` object is rendered as a row automatically using the `__ft__` method |
| 44 | + Tbody(*(Contact(**x) for x in sess['contacts']))) |
| 45 | + |
| 46 | + |
| 47 | +@app.delete |
| 48 | +def delete(id: int, sess): |
| 49 | + sess['contacts'] = [c for c in sess['contacts'] if c['id'] != id] |
| 50 | + # Return nothing to the HTMX request to swap in nothing (removes the row) |
| 51 | + |
| 52 | + |
| 53 | +serve() |
0 commit comments