I'll demo the Turbo Streams with a different example, since you need to handle form submissions for Turbo Streams, and our static site can't do that. So I'll use Sinatra, an elegant Ruby web framework.
Create a Sinatra Project
First, let's install the Sinatra framework and Puma web server using the gem install
command.
gem install sinatra
gem install puma
Create a new directory for the project. I'll call mine wirestream
. Navigate into it and open it in your favorite browser.
mkdir wirestream
cd wirestream
code .
Create a new Ruby script called app.rb
that adds a route for the home page.
require 'sinatra'
get '/' do
'Sinatra says hello!'
end
Now run that script just like any other Ruby script:
ruby app.rb
Sinatra is up and running and serving your web application at localhost:4567
.
That's it. This is a complete web application. Didn't I tell you how simple Sinatra is? How cool is that?
Render a Template
Before we use Turbo Streams, let's set up a proper HTML template, just like Rails.
require 'sinatra'
get '/' do
erb :index
end
Passing the :index
symbol tells Sinatra to look for a index.erb
template in the views
directory. Just copy + paste the following HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css">
<title>Wireframe</title>
</head>
<body>
<header>
<nav>
<a href="/">Home</a>
<a href="/contact">Contact</a>
<a href="/about">About</a>
</nav>
<h1>Learn Hotwire</h1>
<p>Yes, you can really use Hotwire without Rails. Give it a try!</p>
</header>
<main>
<div style="color: green; text-align: center;">
<div id="subscriber-notification"></div>
</div>
<div style="width: 50%; margin: 2em auto; float: left;">
<div id="newsletter">
<form action="/subscribe" method="post">
<div>
<input type="text" name="name" id="name" placeholder="Enter your name" />
</div>
<br />
<div>
<input type="email" name="email" id="email" placeholder="Enter your email" />
</div>
<br />
<button type="submit">Subscribe</button>
</form>
</div>
</div>
<div style="width: 50%; margin: 0 auto; float: right;">
<h4>Subscriber List</h4>
<ul id="subscriber-list">
<li>Yukihiro 'Matz' Matsumoto</li>
<li>Jason Fried</li>
</ul>
</div>
</main>
</body>
</html>
Let's restart Sinatra and reload the page. As you can see, we've added a simple newsletter form and a subscriber list.
Whenever someone enters their name + email and hits "Subscribe", we want to add their name to the "Subscriber List", and also show a notification-like header at the top. Like this:
Let's see how you'd accomplish this using Turbo Streams.