Loading Stylesheets in Sinatra

2020-07-06 03:12发布

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?

标签: sinatra
1条回答
来,给爷笑一个
2楼-- · 2020-07-06 04:10

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.

查看更多
登录 后发表回答