Sinatra static assets

Last week we linked Twitter Bootstrap into your view templates, by linking to the online hosted version:

<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
  crossorigin="anonymous"
/>

What if we want to link to our own css files?

When we were building static sites, this was simple: we just created a main.css file in our site folder, and linked to it. The problem is that a sinatra site folder is not like a static site folder. We’ve already seen this: app.rb controls the url structure, not the folders in the app folder. (Just try going to ‘/app.rb’ or ‘/views/index.erb’). Because of this, just dropping a main.css into the sinatra folder and trying to link to it won’t work.

Thankfully sinatra has a solution to this problem: if you create a folder called public, any files you put in there will be available from the root url. For example, if I have a file public/main.css, You can then link to this from the template files using

<link rel="stylesheet" href="/main.css" />

Two important things to remember here are:

  1. Use a root-relative link (starting with a /). If you don’t do this, you’ll have problems if you ever call that template from a different url route.
  2. Link directly to main.css, not to public/main.css.

Sinatra conventions recap

New:

  1. Files inside the public folder will be served at the root of the site. This is where stylesheets and images should live.

From before:

  1. You call a template with the line erb :template_name
  2. For this to work, you will need a template called template_name.erb in the views folder.
  3. If you want to share a variable with the template, you need to make it an instance variable, by starting the variable name with @
  4. You can display these shared instance variables by using them inside an erb tag:
    <%= @my_variable %>
    

Exercise

Link the bootstrap stylesheet you’ll find in public/main.css into the head of each of your view templates.


Prev | Next