Natstar
Natstar

Reputation: 101

Referencing stylesheets

I'm new to Sinatra and am trying to reference a stylesheet from an ERB file. I have tried the methods used in "Loading Stylesheets in Sinatra" but the stylesheet is still not loading.

My HTML is in views/index.rb and the stylesheet is views/styles/main.css. The controller logic is in app.rb.

The HTML itself is displaying when I load it on a local server.

The folder structure is:

|-- app.rb
|-- config.ru
|-- Gemfile
|-- Gemfile.lock
|-- lib
|-- spec
|   |-- spec_helper.rb
|-- views
|   |-- index.erb
|   |-- styles
|   |   |-- main.css

app.rb is:

get '/' do
  erb :index
end

index.erb did not work:

<link href="<%= url('views/styles/main.css') %>" rel="stylesheet" type="text/css" />
<link href="<%= url('/main.css') %>" rel="stylesheet" type="text/css" />

My repo is: https://github.com/natstar93/Thermostat-day3

Can someone help me work out how to reference the stylesheet?

Upvotes: 3

Views: 476

Answers (1)

matt
matt

Reputation: 79723

Static assets like stylesheets should go in a public directory, not views which is for templates that produce different output for each request.

You should create a directory named public alongside views and copy the styles directory to it. Then the url to the stylesheet will be /styles/main.css:

 <link href="<%= url('/styles/main.css') %>" rel="stylesheet" type="text/css" />

You might also need to enable static asset serving (the docs suggest that it is disabled by default in modular apps, but actually it appears to depend on whether the public dir exists – it can’t hurt to be explicit). Add this to your app class to turn this on:

enable :static

Upvotes: 2

Related Questions