Loading Stylesheets in Sinatra

与世无争的帅哥 提交于 2019-12-05 16:50:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12340335/loading-stylesheets-in-sinatra

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!