How to inline css when using the rails asset pipel

2020-02-08 04:36发布

Instead of having the page include a style tag with a link where to get the css from, which I could add to my view using rails' stylesheet_link_tag helper method, I want to have the css inline directly inside the page.

This is what I came up with so far:

%style(type="text/css")=File.read(physical_asset_path("email.css"))

But I can't find any rails' helper method which gives me the physical path of an asset - physical_asset_path is just a dummy method invented by me.

Anybody knows how to get the physical path of an asset when using rails 3.2.x?

Is there an easier/ better way to get stylesheets - from css files inside the common rails assets paths - inline?

Use case: most email clients don't access external sources (like css, images) without user confirmation. So to get the emails properly displayed I need to embed the CSS inside the emails' HTML.

9条回答
倾城 Initia
2楼-- · 2020-02-08 05:00

Can't add comment to Seth Bro's answer. You better use #[] instead of #find_asset: Rails.application.assets["email"].to_s.

Re "asset will not be compressed". It's not true. It will be compressed if you have compressors enabled (in rails config):

Rails.application.configure do
  # ...
  config.assets.css_compressor = :sass
  config.assets.js_compressor  = :uglify
end

Notice, that by default this is enabled in production environment (config/environments/production.rb).

查看更多
Root(大扎)
3楼-- · 2020-02-08 05:05

(Sorry this answer is in html, not HAML… but that shouldn't be a problem for HAML fans)

I found this question when looking for a way to inline Sass compiled as css into html for creating html email templates.

Combining the above advice, I used the following code in the head of my html page:

<style type="text/css">
  <%= Rails.application.assets['path/to/sass/file'].to_s.html_safe %>
</style>

This code compiles Sass as CSS and then inserts the css into a <style> tag. The html_safe ensures that any quotes (' and ") or angle brackets (> and <) used in the css are not escaped.

The path/to/sass/file is the same as you would use when creating a stylesheet link tag:

<%= stylesheet_link_tag 'path/to/sass/file', :media => 'all' %>
查看更多
神经病院院长
4楼-- · 2020-02-08 05:07

I was trying to inline css for use in google amp compatible pages with rails. I found the following helper from vyachkonovalov which was the only thing for me working in production and locally.

Add the following to the erb template:

<style amp-custom>
  <%= asset_to_string('application.css').html_safe %>
</style>

And the helper to ApplicationHelper. It works perfectly locally and in production.

module ApplicationHelper
  def asset_to_string(name)
    app = Rails.application
    if Rails.configuration.assets.compile
      app.assets.find_asset(name).to_s
    else
      controller.view_context.render(file: File.join('public/assets', app.assets_manifest.assets[name]))
    end
  end
查看更多
登录 后发表回答