Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how can I include a style sheet from the asset pipeline as a <style> tag?

Everyone knows how to use stylesheet_link_tag to link to a stylesheet, but I would like to actually include an entire stylesheet in a page itself. (No, this is normally not a great practice, but it makes sense in this context.)

stylesheet_include_tag does not exist, and a co-worker who is a much bigger bad-ass at Rails than I am says there isn’t a simple way.

Question:
Is it actually possible to make use of the asset pipeline and still embed the contents of a CSS or JavaScript file (compiled from Sass or CoffeeScript!) into a .haml view? How?


Added for clarity:

I’d like for my layout to be able to include something like:

= stylesheet_link_tag "base"
= stylesheet_embed_tag "page-specific-styles/foo"

And have this generate output HTML along these lines:

<link rel="stylesheet" href="/base.css" />
<style type="text/css">.foo { color: red; }</style>

Update

It’s possible to use Sass within Haml if you set your initalizer correctly, but I cannot seem to @import "foo" from this context, where foo.css.sass is a stylesheet in the asset pipeline. Note that @import "compass" (assuming you have the compass gem) does work.

This looks like (haml):

%style
  :sass
    @import "foo"

Rails gives an error that "foo" cannot be found, even though it claims to be looking in app/assets/stylesheets (which is where foo.css.sass lives).

So, this feels closer, but still not quite there.

like image 749
Alan H. Avatar asked Aug 20 '13 22:08

Alan H.


1 Answers

from http://blog.phusion.nl/2011/08/14/rendering-rails-3-1-assets-to-string/ :

YourApp::Application.assets.find_asset('api.css').source

in haml

%style
    =raw YourApp::Application.assets.find_asset('foo.css').source

caveats:

I believe this requires asset compilation in production, which can be pretty costly.

like image 106
Michael Glass Avatar answered Oct 08 '22 16:10

Michael Glass