Sinatra custom SASS directory

2019-08-09 15:43发布

问题:

I have problem getting my sass work with my haml template.

Recently i have following code in my main sinatra.rb application:

require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'haml'
require 'sass'
require 'shotgun'


set :views, :sass => 'views/css', :haml => 'template', :default => 'views'

helpers do
def find_template(views, name, engine, &block)
    _, folder = views.detect { |k,v| engine == Tilt[k] }
    folder ||= views[:default]
    super(folder, name, engine, &block)
end
end


get '/css/styles.css' do
sass :styles
end


get '/' do
haml :index
end


I have following application directory structure:
site
|site.rb
|-sass > styles.scss (my scss file generate css realtime using sass --watch sass:css command                                   
|-css > styles.css 
|-template > index.haml

My index.haml file which is in the template folder is rendered fine.

My index.haml template:

!!! XML
!!!
%html
%head
    %title Some title
    %meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}
    %link{"rel" => "stylesheet", "href" => "views/css/styles.css", "type" => "text/css"}
%body
    %h1 Some h1 
    %p Some p

回答1:

You've given the path to your view file, not the path to the route that will render the SASS file.

%link{"rel" => "stylesheet", "href" => "/css/styles.css", "type" => "text/css"}


回答2:

You need to set the sass views directory to the correct one.

set :views, :sass => 'views/sass', :haml => 'template', :default => 'views'

If you want sass to return the rendered styles.css, then it needs to start where the sass file is. If you want it to return the actuall .css output, then don't have sass render it in your route, just return the file.



回答3:

I found the solution.

require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'haml'
require 'sass'
require 'shotgun'


set :views, :scss => 'views/', :haml => 'template', :default => 'views'

helpers do
def find_template(views, name, engine, &block)
    _, folder = views.detect { |k,v| engine == Tilt[k] }
    folder ||= views[:default]
    super(folder, name, engine, &block)
end
end


get '/css/:name.css' do
  scss :styles
end


get '/' do
  haml :index
end

So as you can see, instead of:

get '/css/styles.css' do
  sass :styles
end

It should be:

get '/css/:name.css' do
  scss :styles
end

Then i placed my styles.scss into my /views folder. However you can modify the destination directory by editing the :scss => 'path to your .scss file:

set :views, :scss => 'views/', :haml => 'template', :default => 'views'