Now that we've learned about ERB and added a layout.erb file, let's learn how to write a view.
First, we'll add some code to app.rb.
require('sinatra')
require('sinatra/reloader')
require('./lib/album')
require('pry')
also_reload('lib/**/*.rb')
get('/test') do
erb(:whatever)
end
The first five lines should look familiar. We require
Sinatra, the album
logic, sinatra/reloader
, and pry
for debugging. Our application should also reload all Ruby files in lib
when any changes are made to them.
Let's look at the new code in our new route. When a browser makes a GET request to /test
, Sinatra will render a view called whatever.erb
back to the browser. Let's make that file now:
<h1>Whatever</h1>
<p>This view can have whatever HTML we want.</p>
We can start the server and navigate to localhost:4567/test. We'll see the whatever
view rendered there.
Sometimes, we will want define a variable in our route that is used in our view. To do this, we have to make the variable an instance variable, like this:
get('/test') do
@something = "this is a variable"
erb(:whatever)
end
<h1>Whatever</h1>
<p>This view can have whatever HTML we want.</p>
<p>It can also use instance variables in the route that renders the view: <%= @something %></p>
If we visit localhost:4567/test, now we'll see our variable rendered.
Note that a single view can potentially handle any number of Sinatra routes. Our views don't care how a user reaches them. As long as the Sinatra route defines all variables that the view needs (such as @something
in the example above), our view will not complain.
Lesson 17 of 37
Last updated August 7, 2022