views:

695

answers:

3

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?

+3  A: 

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.

Cody Caughlan
Nevermind, for some reason I was under the impression that I needed to link to the background images using the rails syntax to use relative urls, but I was mistaken. heh
mportiz08
+2  A: 

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)

astropanic
Cool. I don't think I'll be using that, but it's good to know anyways.
mportiz08
Is there a way to server the stylesheets through a controller and still leverage rails stylesheet caching?
J. Pablo Fernández
You should mention the MIME types, too, I think.
Yar
A: 

Yes you can, take a look at http://nubyonrails.com/articles/dynamic-css

In particular Geoffrey Grosenback (of Peepcode fame) has done a video (see link on that page)

Jon Baker