Sinatra SASS custom directory

2019-07-21 08:26发布

问题:

How to config Sinatra to use custom SCSS directory? I tried the following solution, but this didn't work for me.

class SassEngine < Sinatra::Base

set :views, File.dirname(__FILE__) + '/sass'

get '/sass/*.scss' do
    filename = params[:splat].first
    sass filename.to_sym
end

end

回答1:

Actually the official documentation has a section exactly for this use case.

  • Sinatra Documentation - Looking up Templates

To make it easier here is the code (taken from the documentation):

set :views, :sass => 'views/sass', :haml => 'templates', :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

After this configuration you would just do:

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

or a more general approach:

get '/css/*.css' do
  file = params[:splat].first
  sass file.to_sym
end

Although the last one isn't a good approach since, it will cause errors if called on non-existing files.



回答2:

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'


标签: ruby sinatra