Possible to use stylesheet.css.erb in Rails?

2020-02-09 05:47发布

问题:

Hey, I'm new to Rails and Ruby in general. I was wondering if it's possible to use an embedded ruby css file (css.erb), similar to using html.erb files for views.

For example, I'm using

<%= stylesheet_link_tag "main" %>

to link to my main.css file in public/stylesheets, but when I change the file extension from main.css to main.css.erb, it no longer renders the css..

Is this even possible, or is there a better way?

回答1:

I dont think so. Whats your intention - to use variables and have them be evaluated at runtime, or "compile" time (meaning like deploy time?). Also, what would be the ERB binding? Would it bind to the controller, like views and helpers are, so that ERB instance would have access to the instance variables set in the controller? I just pose this question as more of a theoretical exercise.

If you want to use variables in your CSS than you can use Haml's SASS. You dont get access to the controller's scope but you do get basic variables and looping. Plus other cool stuff like mixins.



回答2:

By the time this question was answered there was indeed no way to use .css.erb files in rails properly.

But the new rails 3.1 asset pipeline enables you to use asset helpers inside your css file. The css parsers is not binded a controller/action scope, but the ruby parser is now able to resolve some issues like image path references

.class { background-image: url(<%= asset_path 'image.png' %>) }

or embed an image directly into your css

#logo { background: url(<%= asset_data_uri 'logo.png' %>) }

source: http://guides.rubyonrails.org/asset_pipeline.html



回答3:

You can also generate a "stylesheets" controller

./script/generate controller stylesheets main admin maintenance

You get something like this:

      exists  app/controllers/
      exists  app/helpers/
      create  app/views/stylesheets
      exists  test/functional/
      exists  test/unit/helpers/
      create  app/controllers/stylesheets_controller.rb
      create  test/functional/stylesheets_controller_test.rb
      create  app/helpers/stylesheets_helper.rb
      create  test/unit/helpers/stylesheets_helper_test.rb
      create  app/views/stylesheets/main.html.erb
      create  app/views/stylesheets/admin.html.erb
      create  app/views/stylesheets/maintenance.html.erb

And you can later use the app/views/stylesheets/ files as dynamically rendered css files.

The same method works for javascript files (javascripts controller)