Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing stylesheets

Tags:

css

ruby

sinatra

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?

like image 674
Natstar Avatar asked Jul 30 '26 16:07

Natstar


1 Answers

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
like image 106
matt Avatar answered Aug 01 '26 04:08

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!