HTMX + Django: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Feature 4: Integrating with front-end frameworks
Lecture: Boostrap modals
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Bootstrap is a bit of a beast. It's a wonderful beast that makes it easier to create good looking pages, but man oh man are there a lot of divs.
0:10
To implement a modal dialog box in Bootstrap, you need two things, a button that launches the dialog and the dialog divs itself.
0:19
How Bootstrap knows a button is for dialog launching is through the use of the data toggle attribute.
0:25
Setting it to modal associates this button with a dialog. The Data Target attribute is used to specify the ID of the actual modal to display.
0:37
Note that I'm showing you Bootstrap 4 here. The attributes have been renamed in Bootstrap 5, adding a namespace. Who doesn't love a little extra BS?
0:48
This is the corresponding tags to define the structure of the modal.
0:52
It has the ID specified in the button, and a very nested set of divs to define the structure. I've left it out here, but the content section
1:00
typically also has a header. The body part would be what shows in the dialog. In the footer of this modal,
1:07
I have a button that has a data dismiss attribute. This is what makes it a close button. When you click on it, it will hide the modal.
1:17
Make sure you spell it correctly. When I wrote this code, I missed one of the S's and it took a while to figure out why my dialog wouldn't close.
1:24
To implement our about box, I'm first going to create a partial with the modal contents. It will look a lot like that bootstrap modal
1:33
I just showed you. Then I'll open up the base.html file. The button for the modal is going in the nav bar,
1:42
so I need to add a link that pops up the dialog box. This link will have the necessary bootstrap attributes,
1:48
but it also will have the necessary htmx attributes to dynamically fetch the modal. The tricky part is bootstrap won't work
1:57
if it can't already find the modal when the page loads. Instead of putting our modal there, I'm going to put a small placeholder.
2:05
The placeholder will be what gets replaced by HTMX when the link is clicked. The neat thing about this approach is that if you have many dialog boxes,
2:14
you can get away with only a single placeholder. As you're dynamically injecting the contents, you could have a single view that takes an argument
2:22
as to what modal to display and always call the same view. This would mean your pages would be smaller
2:28
and the code for the dialog only gets put in the page if the user actually invokes it. Lastly, I need a view that renders the partial modal,
2:37
which will be very short, just two lines of code. Let's go into PyCharm and write us a dialog box.