HTMX + Django: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Feature 2: Active search
Lecture: Intro to search as you type

Login or purchase this course to watch this video and the rest of the course contents.
0:00 In the previous lesson I showed you how to use the HXGet attribute to dynamically replace the contents of a tag using HTMX.
0:09 In this lesson I'll be covering how to build an interactive page with Search As You Type. This image shows the desired outcome.
0:19 A page with an input for search and some results. As the user types in the search field, the results are added dynamically.
0:28 There's also something a little subtle going on here. Notice that the URL has a query parameter
0:33 with the desired search term as well. The goal is for the URL to get updated as you enter a new
0:40 search term. There's a couple reasons to do this. First, it allows deep linking. You could copy the
0:47 URL, send it to a friend, and they'll see the same results you're looking at. The second is browser
0:53 history. By modifying the URL on the fly, you can now take advantage of the back button.
0:58 Search for electric cars, search for IndyCars, then press back and you'll see the electric car
1:05 search again. This is something that single page applications often make impossible or
1:11 require the programmer to jump through hoops to achieve. To build this feature, the first step
1:17 I'll take is to create a view and template for the page. I'll start by hardcoding the search results,
1:23 ignoring what's in the search field, and just make sure the structure of the page works and
1:28 that I've got the query right for searching on text terms. Once the base is in place,
1:34 it's time to start wiring the HTMX. The search field needs to be changed to respond to the user's
1:41 input, and as a search goes to the server, the results need to come back as a partial.
1:46 In the previous lesson, I used multiple views to cover each step here.
1:50 This time around, I'll show you an alternate approach where you can do it all in the same view.
1:55 HTMX sets a header when it makes a call, so you can differentiate vanilla browser calls from an
2:03 HTMX one. You can check for this header explicitly, but there is a handy third-party library called
2:09 DjangoHTMX which provides a bunch of utilities. One of these is some middleware that sticks a
2:15 a data object in the request which has HMX-related info on it. I'll be using that inside the view to check if this is an HTMX call.
2:25 Once I've got the page working and results showing up dynamically, then I'll go back and add the URL updating feature.


Talk Python's Mastodon Michael Kennedy's Mastodon