Skip to main content

Javascript

We use Hotwire as our Javascript solution.

Now Hotwire mainly contains two parts, Turbo and Stimulus

Turbo

Turbo contains four parts:

  1. Turbo Drive: accelerates links and form submissions
  2. Turbo Frames: decompose pages into independent contexts like HTML iframe
  3. Turbo Streams: deliver page changes over WebSocket, SSE or in response to form submissions using just HTML and a set of CRUD-like actions
  4. Turbo Native: help build hybrid apps for iOS and Android.

You can check https://turbo.hotwired.dev/ to learn more.

We import Turbo in frontend/src/application/app.js

Form Validation

If you use Turbo Drive in your project, you should return 422 Unprocessable Entity to tell the form validation has failed.

If you write Django CBV, you do not need to worry about that because SaaS Hammer has done that for you.

If you write Django FBV, you should follow pattern like this

import http

from django.shortcuts import redirect
from django.template.response import TemplateResponse

from myapp import MyForm

def my_view(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
# save data etc...
return redirect("/")
status = http.HTTPStatus.UNPROCESSABLE_ENTITY
else:
form = MyForm()
status = http.HTTPStatus.OK
return TemplateResponse(request, "my_form.html", {"form": my_form}, status=status)

Stimulus

Stimulus is a JavaScript framework with modest ambitions. Unlike other front-end frameworks, Stimulus is designed to enhance static or server-rendered HTML—the “HTML you already have”—by connecting JavaScript objects to elements on the page using simple annotations.

We can:

  1. Use the classic dev frameworks such as Django, Rails to render HTML.
  2. Use Stimulus to attach JS to the DOM elements.

You can check https://stimulus.hotwired.dev/ to learn more.

tip

We have created some Stimulus controllers for you, and you can find them in frontend/src/controllers.