Caley Woods
Caley Woods

Reputation: 4737

Sinatra CSS/Images Issue

I have a sinatra app running locally and awhile back I ran into an issue when I went to add styling. I placed the CSS file in public/css/style.css but it wasn't being served. After some troubleshooting I discovered the Rack::Static middleware and that solved the problem at the time, the line I added in config.ru was:

use Rack::Static, :urls => ["/css", "/images"], :root => "public"

This lets Rack serve the css and images from public/css and public/images respectively. When you link up images or styles in Haml you just use css/style.css and leave the public off.

The issue I have after last night, I created a small file structure inside of my views directory to better organize things, so now when you visit the /contact/new path which renders views/contacts/_form.haml the CSS doesn't work. Viewing source on the page confirms that Rack is attempting to serve the CSS at contacts/css/style.css instead of the correct path of css/style.css such as the main index correctly displays.

How can I fix this to make sure it's always rendering from the root of the URL and not based on the relative location of the view currently being rendered? I tried making root => "#{File.dirname(__FILE__)/public" in config.ru but that didn't help.

Upvotes: 2

Views: 2778

Answers (3)

Charmi
Charmi

Reputation: 610

I am putting css files in public/css/

and using the following redirection for other pathes

get %r{.*/css/style.css} do
    redirect('css/style.css')
end

Upvotes: 0

smenon
smenon

Reputation: 129

simple way to show images

get '/notes/images/:file' do

send_file('/root/dev/notes/images/'+params[:file], :disposition => 'inline')

end

Upvotes: 0

Steve
Steve

Reputation: 15736

I don't think the location of the view template should make any difference but if you have relative URLs like css/style.css then the browser will append this to the path part of the URL of the page that hosts it. So if the page URL is contact/new the effective URL becomes contact/css/style.css.

If you prefix the relative URL with a '/' like /css/style.css it should be relative to the root path of the site which you are mapping to the public directory. So that might be the best way to go:

  %link{ :href => '/css/style.css', :rel => 'stylesheet', :type => 'text/css' }

I haven't tried using the rackup file to configure static files. This is what works for me in the application itself:

  set :static, true
  set :root, File.dirname(__FILE__)
  set :public, 'public'

But I think that Sinatra will serve static files from the public by default so I don't think the last line is required.

Upvotes: 7

Related Questions