I'm using Sinatra, and I've been trying to load in some stylesheets. I've tried just the normal html link
tag in my erb, but that hasn't worked.
ive tried
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
It's not an issue with the url i'm using, is there some special way of achieving this?
When you use href="style.css"
, you’re specifying a relative link to the stylesheet. The actual path that your browser will request will depend on the url of the current page, so for example if you have a route like:
get '/things/:id' do
#look up thing with id = :id
erb :my_view
end
then the browser will look for the stylesheet at /things/style.css
. This obviously won’t work if your stylesheet is at the top level in your public
dir.
The quick fix is to use an absolute path to your stylesheet: href="/style.css"
(note the /
character). This will make the browser always look for the stylesheet at the root of the server.
This assumes that your application is always mounted at the root of your server, and will fail if your run it in a subdirectory. You want to be able to say “look for the stylesheet in the root of this application, wherever it happens to be”. In Sinatra you can do this by using the url
helper method. Using ERB as your template language this would look like:
<link href="<%= url('/style.css') %>" rel="stylesheet" type="text/css" />
This will ensure the link to style.css
will be correct wherever your app is located.