https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/htmx-alpine/ SaaS Pegasus Modern JavaScript for Django Developers - Django, HTMX and Alpine.js: Modern websites, JavaScript optional Pegasus is on sale! Through November 30 you can use Pegasus on unlimited sites, with lifetime updates, for 50% off--a $375 savings. Modern JavaScript for Django Developers Django, HTMX and Alpine.js: Modern websites, JavaScript optional Django, HTMX and Alpine.js: Modern websites, JavaScript optional Building a modern front end in Django without reaching for a full-blown JavaScript framework. Choosing the right tools for the job, and bringing them into your project. Django + JavaScript November 23, 2021 This is Part 5 of Modern JavaScript for Django Developers. Welcome back to "Modern JavaScript for Django Developers"! Previous installments of this series covered 1) organizing your front end code in a Django project, 2) JavaScript toolchains, 3) integrating toolchains into Django, and finally 4) integrating React and Django. In Part 5 we're going to take things in a new direction. In this installment we'll turn to the low- and no-JavaScript world. We'll cover some of the common approaches to "sprinkling in" light amounts of JavaScript into your Django projects in 2021. We'll start high-level--approaching the big-picture questions of when you might choose a "low-JavaScript" architecture, and how to decide when to bring in a framework. After that we'll dive into two of the best low-JavaScript tools to use with Django today: Alpine.js and HTMX. Now get cozy, put away your Webpack, React, and Vue, and get ready for some good old-fashioned server-rendered Django goodness! Here's where we're headed: * When you might choose low-JavaScript + What problem are you trying to solve? * To framework or not to framework * Building interactive interfaces in your Django pages with Alpine.js + Integrating Alpine.js and Django * Talking to your Django backend without a full-page reload with HTMX + Choosing your AJAX tool + What is HTMX? + An HTMX example with Django Forms * Conclusion: Choosing Low-JavaScript vs High-JavaScript * Up next: you decide! When you might choose low-JavaScript Before getting into any specific low-JavaScript tool you should first ask yourself: is low-JavaScript right for me? One place to start in answering that question is understanding the type of page you're building. In our conversation on Django front end architectures, we talked about three categories of pages you can find in almost every Django app: 1. Server-first Django pages with little-to-no JavaScript. These are your standard Django pages like a login form or user profile. 2. Client-first JavaScript pages with little-to-no Django. Anything with a rich and interactive front-end experience fits in this category. Think about something like Gmail or Google Maps. 3. Everything in between. For example, something like this UI to sign someone up to a SaaS Subscription. The low-JavaScript world is perfect for category 3--all of those in-between pages with a splash of page-level interactivity. But, it also works great as a compliment to mostly-server-rendered pages (category 1), and it can even work for pages that are typically be handled by something like a single page React app (category 2). So in short--low-JavaScript is almost always an option. You'll just have to decide if and when it works well for you. For me, low-JavaScript Django has become a more and more exciting option over time. In the last year I've found myself reaching for HTMX in many situations where I historically would have used React. It let's you do a lot of what fancy frameworks provide, and forces you to give up almost nothing in terms of how you're used to using Django. Hopefully the rest of this guide will present a clear picture of what this looks like, and help you make the decision for your own projects. Now let's get into some specifics. What problem are you trying to solve? Before reaching for any particular tool, it's important to know what you're trying to achieve. This might sound obvious, but it's easy to forget! You know the saying "when all you have is a hammer, everything looks like a nail"? Well, the same is true of technology. You can accomplish most things with any number of front-end frameworks, but they all excel at slightly different things. Using the right one for any particular problem will make you a lot more efficient! The Framework Hammer When all you have is React, everything looks like a single-page-app. Here are some of the reasons you might reach for JavaScript: * Maybe you want a bit of on-page interactivity, for example, having a button open a modal dialog. We could call this making interactive interfaces. * Or you might want to do some work asynchronously--perhaps embedding a form that sends data to your back end without doing a full-page reload. We could call this making AJAX requests. * Or maybe you're integrating with something that already uses JavaScript--e.g. displaying your app's data in an interactive chart. We could call this using existing libraries. These aren't the only use cases by any means, but they cover a lot of ground, so that's where we'll start. What's important is that each of these use cases have different needs--and those different needs make them uniquely suited to specific solutions. Alpine.js is great for building interactive interfaces. HTMX is amazing for AJAX. And to integrate with existing libraries we'll return to our Django JavaScript toolchain. But we're getting ahead of ourselves. The very first question you should ask yourself is whether you need a framework at all.... To framework or not to framework The first question that comes up for every JavaScript use case is whether--and to what extent--to reach for a framework to solve the problem. Image here Little known fact: Hamlet moonlighted as freelance Django developer. This guide will ultimately recommend using frameworks most of the time, but to get this out of the way first: you may not need a JavaScript framework. JavaScript--especially in a modern JavaScript environment--is powerful. You can build rich applications with vanilla JavaScript. And the existence of a vast ecosystem of 3rd-party libraries and packages--not to mention Stack Overflow--only makes it easier. Sticking to native JavaScript is nice mostly because it's dependency-free. This simplifies and streamlines a lot. You don't have to worry about importing external scripts and the overhead--both in terms of page weight and code maintenance--that introduces. Your code will also be immediately understandable and modifiable by anyone who knows JavaScript (hopefully!). Frameworks--even lightweight ones--have a learning curve and can trip up developers who've never seen them before. The main downside of choosing native JavaScript is that you'll be working at a pretty low level. You end up writing a lot of code that looks something like the below. This example wires up events that close the dialog below: Press the little "x" to close this message. That's native JavaScript, baby! // when the DOM is loaded document.addEventListener('DOMContentLoaded', () => { // find every element with the class "close" (document.querySelectorAll('.close') || []).forEach((closeButton) => { const parent = closeButton.parentNode; // and add a "click" event listener closeButton.addEventListener('click', () => { // that removes the button's parent from the DOM parent.parentNode.removeChild(parent); }); }); }); The code that wires up the little "x" to close the above dialog, written in pure JavaScript. This code isn't overwhelming or difficult to write, but it's quite a lot of lines for something so simple. If you only need to do this a few times then sure, throw the script on your page and call it a day. But as more of these are added they will become increasingly unwieldy. Also, it's worth pointing out that many frameworks exist primarily to make writing and maintaining code like the above easier. We'll see in the next section how we can replace the above with just a few attributes in Alpine.js--which is particularly good for this type of thing. Introducing a framework to your project is kind of like switching from a text editor to a full-blown IDE for the first time. At first you're slowed down, everything is unfamiliar, and you have to learn this whole new system for doing every little thing. It's frustrating! But then, once you're on the other side of the learning curve you are way more efficient. Eventually you wonder how you ever wrote code in that clunky old way. XKCD Learning a new framework will make you more efficient, but it takes an initial investment of time to ramp up that efficiency. This chart For this reason, this guide advises having a very low bar for adopting a framework. The frameworks discussed here are quick to learn and easy to adopt. And ultimately, once you get over the learning curve they will make you substantially more efficient. Do you need a framework if your project is tiny? Absolutely not. But when things start to grow and change over time, keep the bar low for bringing one in. With that, we're going to shift gears and focus on framework-based solutions, but know that they aren't strictly necessary! Building interactive interfaces in your Django pages with Alpine.js The simplest and most common use of JavaScript is for little bits of on-page interactivity: menus that open on mobile, modal dialogs that pop up and close, stuff like that. The code snippet above is a perfect example of this type of thing. You can do these with vanilla JavaScript, but it gets unwieldy quickly, so let's talk about other options. Some UI frameworks--most notably, Bootstrap--come with many of these things built in. If you're using one of those UI frameworks, and it supports your use case, use it! That's what it's there for. Outside of UI frameworks, for a long time the default answer to interactive interfaces was jQuery. However, these days there are more popular--and franky, superior--options. The one this guide recommends starting with is Alpine.js. They even refer to themselves as "jQuery for the modern web". Alpine.js Alpine.js positions itself as "your new, lightweight, JavaScript framework". And it does a good job! Alpine is particularly good at these little utilities to help build interactive interfaces. Here's the dialog-closing example from above using Alpine. An important point--which will come up a lot in this guide--is that it doesn't require you to write any of your own JavaScript! Press the little "x" to close this message. This one is handled by Alpine.js with just a few attributes!