DEV Community

Carlos Castaneda
Carlos Castaneda

Posted on

TIL Blog Day 10 - View Templates

Why create view templates?

Before learning about view templates in Sinatra, we had to write our HTML in a String literal. This was problematic because it made our app.rb file really long and hard to read. We also need to escape all the " in our HTML code so it would be valid. View templates makes it so we can separate our HTML from our Ruby code/routes.

To get started:

  1. Create a folder named `views'

  2. In that folder we create a file with the file type .erb

  3. Within that file we can write our HTML (we now get syntax highlighting and emmet is back!)

  4. Finally, to link our Ruby route to this view template we just add a method at the end of our route code like this:

ruby
get("/") do
erb(:template_name)
end

ERB

ERB, or embedded ruby, is a templating language based on Ruby.
It allows you to run Ruby code within your view template and when you run the code the browser only receives pure HTML. The two main tags you will use with ERB are:

<%= %>
Within these brackets you can write the value of a Ruby expression and it will be inserted into your HTML.

<% %>
Within these brackets you can execute Ruby code but it will not be inserted into your HTML.

You can also write your Ruby code in your route and give your view template access to variables by adding an @ in front of your variable names. This will allow you to access them and use them in your erb file.

View templates make it incredibly easy to separate your HTML from your Ruby code. Overall, Sinatra makes it so you can get a website up and running quickly!

Top comments (1)

Collapse
 
samuellubliner profile image
Samuel Lubliner

I liked this lesson because separating the HTML and Ruby with templates make the code more clean and readable!