Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Ruby strings work okay for responding with short HTML snippets. But they're not going to work so well for full pages. That's why Sinatra has a feature that makes it easy to load text in from files: ERB templates. We can use an ERB template to generate our response to the browser.
-
0:00
Ruby strings work okay for testing short HTML snippets.
-
0:04
But it's not going to work so well for full pages.
-
0:07
That's why Sinatra has a feature that makes it easy to load in text from files
-
0:11
ERB templates.
-
0:13
ERB stands for Embedded Ruby.
-
0:15
It allows you to take a text file such as HTML template that always shows the same
-
0:20
static text and embed Ruby code into it that displays changing dynamic data.
-
0:26
We'll talk about embedding data into ERB in a bit.
-
0:29
For right now we're just going to place some static unchanging HTML into an ERB
-
0:34
template file and load that in as the HTML we're going to display.
-
0:38
Sinatra loads ERB templates in from of
-
0:41
view sub directory within your apps main directory.
-
0:43
So let's create that directory now.
-
0:46
I'll choose a new folder and name it views.
-
0:54
Within that folder, I need to create a file whose name ends in a .erb extension,
-
0:59
so I'll choose a new file and
-
1:03
name it welcome.erb Then I'll go back into my main app.
-
1:10
Remove the HTML string from our route and move it into the welcome.erb file.
-
1:16
Making sure to remove the quote marks from the string.
-
1:19
I'll save that and then in the route I will call a Sinatra method called erb.
-
1:25
The erb method loads a template file from the views directory, renders it and
-
1:29
returns the result as a string.
-
1:31
Since our template doesn't have any erb tags and
-
1:34
the result will be the same HTML string as before.
-
1:37
You pass an argument to the erb method with the name of the file you want
-
1:41
to render as a symbol and leave in the .erb extension off.
-
1:45
So we use a symbol of :welcome and that'll render the welcome.erb file.
-
1:51
Since our template doesn't have any erb tags in it,
-
1:53
the result will be the same HTML string as before.
-
1:57
Let's try it out and see if it still works the same.
-
2:00
I'll go to my console, stop my server if it's running and then run it again.
-
2:06
Then in the preview, I'll click refresh.
-
2:10
We get the same HTML as before.
-
2:12
Welcome to our Wiki is a level one heading.
-
2:14
But now that our HTML is in a file,
-
2:16
it'll be easier to add more code to the template.
You need to sign up for Treehouse in order to download course files.
Sign up