@@ -732,6 +732,62 @@ def render_button(text):
732
732
hx_trigger="click, keyup[key=='U'] from:body",
733
733
get=doit)
734
734
735
+ serve()
736
+
737
+ </example>
738
+ <example name="Delete Row">
739
+ from fasthtml.common import *
740
+
741
+ app, rt = fast_app()
742
+
743
+ # This represents the data we are rendering
744
+ # The data could original from a database, or any other datastore
745
+ @dataclass
746
+ class Contact:
747
+ # Data points
748
+ id: int
749
+ name: str
750
+ email: str
751
+ status: str
752
+
753
+ def __ft__(self):
754
+ # __ft__ method is used by FastHTML to render an item in the UI
755
+ # By defining this, a `Contact` will show up as a table row automatically
756
+ return Tr(
757
+ *map(Td, (self.name, self.email, self.status)),
758
+ Td(Button('Delete',
759
+ hx_delete=delete.to(id=self.id).lstrip('/'),
760
+ # Give a confirmation prompt before deleting
761
+ hx_confirm="Are you sure?",
762
+ # Target the closest row (The one you clicked on)
763
+ hx_target="closest tr",
764
+ # Swap out the row with nothing (removes the row)
765
+ hx_swap="outerHTML")))
766
+
767
+ # Sample data
768
+ # Often this would come from a database
769
+ contacts = [{'id':1, 'name': "Bob Deer", 'email': "
[email protected] ", 'status': "Active" },
770
+ {'id':2, 'name': "Jon Doe", 'email': "
[email protected] ", 'status': "Inactive"},
771
+ {'id':3, 'name': "Jane Smith",'email': "
[email protected] ",'status': "Active" }]
772
+
773
+ @rt
774
+ def index(sess):
775
+ # Save a copy of contacts in your session
776
+ # This is the demo doesn't conflict with other users
777
+ sess['contacts'] = contacts
778
+ # Create initial table
779
+ return Table(
780
+ Thead(Tr(*map(Th, ["Name", "Email", "Status", ""]))),
781
+ # A `Contact` object is rendered as a row automatically using the `__ft__` method
782
+ Tbody(*(Contact(**x) for x in sess['contacts'])))
783
+
784
+
785
+ @app.delete
786
+ def delete(id: int, sess):
787
+ sess['contacts'] = [c for c in sess['contacts'] if c['id'] != id]
788
+ # Return nothing to the HTMX request to swap in nothing (removes the row)
789
+
790
+
735
791
serve()
736
792
737
793
</example>
0 commit comments