htmx on Sinatra

—interactive web pages with hypermedia

Part 6: Personalization with POST

We can skip a step in our greeting personalization. Instead of capturing the user's name and redirecting to a new page, we can insert the name variable into a new template when the user submits (with POST):

get '/' do
  erb :'index'
end

post '/' do
  erb :'thank-you', :locals => { :name => params[:name] }
end

Our new "thank you" element now appears in place of the old submission form.

This does make the code shorter, and we able to stay on the same page. Notice however, that we are still serving an entire new template just to display the "thank you" message:

<body class="viewport-centered text-centered">
  <main>
   <div class="check">&#10004;</div>
   <h2 class="no-margin">Thank you, <%= name %>!</h2>
   <p class="no-margin">We'll be in touch when we launch.</p>
  </main>
</body>

This happens because in our POST route, we are issuing a new page request. The server then returns a dedicated template containing the chrome of the page (the body element), with some new elements included further down in the DOM tree.

In other words, we are causing a full page refresh — the browser must re-draw the entire layout from the top down, not distinguishing between the elements that need to be replaced, and those that do not.

Can't we just replace the elements we need, without loading in the entire page?

It turns out, we can — with htmx.