In Rails, when we include an image into the page we use image_tag helper, which generates <img> tag and adds ?nnnnn at the end of its url, so that every time an image is updated the old version would not be stuck in the cache on the client side. Same thing for SASS needed, but I can't find it in the documentation.
You should be using helpers provided by sass-rails gem https://github.com/rails/sass-rails, (scroll to Asset Helpers).
These helpers can be used from inside sass files any time you need to reference an asset (image/audio/video/font)
body{
background: asset_path($relative-asset-path, $asset-class);
}
Note: image_url("...") is not working on Rails 3.1.0.rc4 due to a bug, but you can still use asset_url and asset_path.
Using stylesheet_link_tag will do this for you, just the same as image_tag does. This also applies to JavaScript files linked in with javascript_include_tag.
Related
I have a question about using asset_sync and a Heroku CDN. In this article, it says
Make sure you’re using the Rails AssetTagHelper methods (like
image_tag). This will ensure all of your assets will reference the new
asset host.
Does that mean any plain html <img> tags or refs in my app won't work? Or maybe it's just to warn against tags with an absolute URL?
EDIT: I know I can and should use image_tag and image_path in views or css. What I'm asking is, do I HAVE to?
They will work but you will need to point it manually to where you are syncing your assets to, some bucket on Amazon S3. Not really recommended unless your assets will hardly ever change.
You configure your asset path in your production.rb config like so:
config.action_controller.asset_host = "http://assets.domain.com"
Then whenever you reference asset_path it will point to the asset on the host defined in your environment config.
Perhaps a solution (without understanding your exact problem) would be to do something like this:
<img src="<%= asset_path("image.png") %>" />
You should to use
<%= image_path("logo.png") %>
instead of
<img src="<%= asset_path("image.png") %>" />
You can more details about this helper method here. Also As specified by andrew you need to specify asset_host in you config file. Here is a small blogpost for the same
Also:
If you want to pull css background icons/images from amazon s3 then use:
background-image: image_url("icon.png"); // it requires scss extension ie saas and also you must has saas rails gem included.
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.
Rails.application.assets.find_asset('email').to_s will return the compiled asset as a string.
Use premailer or premailer-rails3
https://github.com/fphilipe/premailer-rails3
or
https://github.com/alexdunae/premailer
Joe's Nerd Party say:
We also used the Premailer gem to automatically inline the linked
stylesheet in the email views. Our email layout looks something like:
%html
%head
= stylesheet_link_tag 'email'
%style{:type => "text/css"}
:sass
#media all and (max-width: 480px)
table#container
width: auto !important
max-width: 600px !important
... and so on for the mobile code
%body
Email body here.
%table
Lots of tables.
We include a stylesheet in the HTML. Premailer downloads it, processes
it, and inserts the css rules inline in the HTML.
The #media rules need to be inline in the email layout, since
Premailer can’t handle those being in a separate css file yet.
We use premailer-rails3 to integrate Premailer into Rails 3.
Unfortunately, we found a bunch of bugs in premailer and
premailer-rails3. Our forks of the projects are at
https://github.com/joevandyk/premailer and
https://github.com/joevandyk/premailer-rails3. The forks fix some
encoding bugs, remove some weird css processing stuff done by
premailer-rails3, allow premailer to not strip out embedded
rules in the email layouts, and some other things.
We also found a bug in sass-rails, where you can’t embed image-urls in
inline sass code. See https://github.com/rails/sass-rails/issues/71
Premailer-rails3 hooks into ActionMailer when the email actually being
delivered, not just generated. When running tests, email is not
actually sent, so the premailer-rails3 hooks don’t get ran during
tests. I haven’t spent the time to see if it’s possible to get the
premailer processing to run during tests, but that would be a nice
thing to do.
Also, our forks on premailer-rails3 assume that you want premailer to
go out and actually download the linked CSS files. It should be
possible to use the Rails 3.1 asset pipeline to get the processed css
without downloading it. A very special thanks goes to Jordan Isip who
did the super annoying job of making sure the emails look great in all
the different clients out there. Writing that CSS/HTML did not look
fun.
Update:
Roadie appears to be a better option. Thanks to Seth Bro for pointing it out.
(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' %>
Rails.application.assets['asset.js'] will work only in local environment, as rails asset compilation is disabled in both production and staging environment.
Rails.application.assets_manifest.find_sources('asset.js').first.to_s.html_safe should be used to inline css when using rails asset pipeline.
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).
Had the same problem, solved it using #phlegx's answer to a similar issue in Premailer.
For an environment-safe solution you need to use
(Rails.application.assets || ::Sprockets::Railtie.build_environment(Rails.application)).find_asset('email.css').to_s
I've packaged it into a helper in my app:
# app/helpers/application_helper.rb
# Returns the contents of the compiled asset (CSS, JS, etc) or an empty string
def asset_body(name)
(Rails.application.assets || ::Sprockets::Railtie.build_environment(Rails.application)).find_asset(name).to_s
end
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
tl;dr (without Roadie):
%style(type="text/css")
= render template: '../assets/stylesheets/email_responsive.css'
For actually applying the CSS as inline styles, I recommend roadie-rails (which is a Rails wrapper for Roadie). It also has other neat features like absolutizing hrefs, srcs etc.
A usage combining both inlined (email.scss) and non-inlined (email_responsive.css) stylesheets, both residing in app/assets/stylesheets:
-# This will be inlined and applied to HTML elements.
-# Note that you need to include this in your asset config, e.g.:
-# Rails.application.config.assets.precompile += %w(... email.css)
-# (You need to list it as `email.css` even if it's actually `email.scss`.)
= stylesheet_link_tag 'email'
-# E.g. for media queries which can't be inlined - yeah, some iOS devices support them.
-# This will not be inlined and will be included as is (thanks to `data-roadie-ignore`).
-# `template:` marks it as a full template rather than a partial and disables `_` prefix.
-# We need to add the extension (`.css`) since it's non-standard for a view.
%style(type="text/css" data-roadie-ignore)
= render template: '../assets/stylesheets/email_responsive.css'
You can use this:
Rails.root.join('public', ActionController::Base.helpers.asset_path("email.css")[1..-1]).read.html_safe
I have noticed that with the latest rails and sprockets versions (3.2.1 & 2.2.0) there seems to be a problem when the erb file extension is added to a sass partial.
e.g. if somestylefilename.css.sass is renamed to somestylefilename.css.sass.erb and the file contains a declaration of a sass variable that uses erb, vis:-
$background-colour: <%= '#fff' %>;
all is ok.
However if a sass partial is renamed from say _sharedpartial.css.sass to _sharedpartial.css.sass.erb then the same variable declaration is not recognised.
I am not sure if this is the right forum to report this behaviour or if it is a sass, rails or sprockets problem.
P.S. I know that the asset pipeline targets efficiency through pre-compiled assets, but I am trying to write a theeme controller that is capable of selecting the default colour/layout scheme for a site which will subsequently form the default pre-compiled css asset in production.
Best regards,
John Leake
This is a sass-rails error, as discussed here.
I had the same question and found out that the solution is by installing sass-rais-path.
This gets Rails to work SASS + ERB as expected.
This will sound a bit ridiculous, but have you tried to remove the .erb extension?
Normally you don't have to use it, even if you use erb tags.
I have a Rails 3.1 app that uses the codebrew/backbone-rails. In a .jst.ejs template, I would like to include an image, like so:
<img src="<%= image_path("foo.png") %>"/>
But of course the asset helpers are not available in JavaScript.
Chaining ERB (.jst.ejs.erb) does not work, because the EJS syntax conflicts with ERB.
Here is what I know:
The asset helpers are not available in the browser, so I need to run them on the server side.
I can work around the problem by making the server dump various asset paths into the HTML (through data attributes or <script> and JSON) and reading them back in JS, but this seems rather kludgy.
Is there a way to somehow use the asset helpers in EJS files?
There is a way, actually, to chain a .jst.ejs.erb file, although it's fairly undocumented, and I only found it through looking at the EJS test cases. You can tell EJS to use {{ }} (or [% %] or whatever else you want) instead of <% %>, and then ERB won't try to evaluate your EJS calls.
Make sure to require EJS somewhere in your code (I just included gem 'ejs' in my Gemfile), and then create an initializer (I called it ejs.rb) that includes the following:
EJS.evaluation_pattern = /\{\{([\s\S]+?)\}\}/
EJS.interpolation_pattern = /\{\{=([\s\S]+?)\}\}/
Then just make sure to rename your templates to .jst.ejs.erb, and replace your existing <% %> EJS-interpreted code with {{ }}. If you want to use something other than {{ }}, change the regular expressions in the initializer.
I wish there were an option in Sprockets to handle this through the config rather than having to explicitly include EJS, but as of the moment, there's no way to do that that I know of.
I can see two ways. Neither are great.
When you say <%%= variable %> then this is rendered by ERB as <%= variable %>, so you could double percent escape everything but the asset_tags and that would survive the trip through one ERB pass on the way to EJS.
If you find that too gross...
How about making a different javascript file, with an ERB extension, that defines your asset paths? And then use the asset pipeline to require that.
So say assets.js.erb defines something like:
MyAssets = {
'foo': <%= image_path("foo.png") %>,
...
}
And then require this somewhere near the top of your manifest. And then reference the globals however that works in EJS.
For those willing to try HAML instead of EJS: Using haml-coffee through haml_coffee_assets has worked well for me as well.
You can have the following in a .hamlc.erb file:
%img(src="<%= image_path('foo.png') %>")
(It still doesn't give you routing helpers though, only asset helpers.)
Ryan Fitzgerald was kind enough to post a gist of his JavaScript asset helpers (which get precompiled with ERB): https://gist.github.com/1406349
You can use corresponding Javascript helper via the following gem:
https://github.com/kavkaz/js_assets
Finally (after installing and configuring) you will be able to use it like this:
<img src="<%= asset_path("foo.png") %>"/>
I have a Rails app with the following in /app/assets/stylesheets/styles.css.erb:
...
#nestedbg {
background-position: left top;
background-image: url(<%= asset_path 'siteheader2.png' %>);
background-repeat: repeat-x;
background-attachment: fixed;
}
...
When I run rake assets:precompile and then run rails s -e production, everything works as expected. However, when I remove the precompiled assets and run rails s in development, the CSS file comes up as shown above instead of being properly substituted.
I tried putting config.assets.compile = true in /config/environments/development.rb and that did not help.
Any ideas?
Thanks.
I honestly cannot say why this is not interpreted correctly in your case, but I have a much better workaround to offer: skip erb interpreting altogether.
You can do this like so:
/* styles.css.scss */
background-image:url(image_path("siteheader2.png"));
If you did not have a chance to I would also suggest to have a look at SASS: it is integrated in the Rails asset pipeline and lets you do cool things like variable declarations, nesting, mixins, ...
I found that my css files wouldn't be processed by ERB unless SCSS processing was also added.
I changed my screen.css.erb to screen.css.scss.erb and now <%= asset_path 'file.png' %> is rendered correctly as /assets/file.png.
I'm on Rails 3.1.3.
I was using Rails 3.1.1 and when I switched the app to use Rails 3.1.3, the problem went away. I switched back to 3.1.1 to see if the issue came back and it did not.
I'm guessing that it was a problem with one of the gems and the update to 3.1.3 brought other gem updates with it.
Bizarrely, I found that changing asset_path to asset_data_uri and then back to asset_path worked for me. Was using Rails 3.1.3 all along.
Strange.
Sam Oliver's advice did the trick for me, simply renaming the extensions didn't update the timestamp on the files.
CSS and ERB
The asset pipeline automatically evaluates ERB. This means that if you add an erb extension to a CSS asset (for example, application.css.erb), then helpers like asset_path are available in your CSS rules:
.class { background-image: url(<%= asset_path 'image.png' %>) }
This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as app/assets/images/image.png, which would be referenced here. If this image is already available in public/assets as a fingerprinted file, then that path is referenced.
If you want to use a data URI — a method of embedding the image data directly into the CSS file — you can use the asset_data_uri helper.
CSS and Sass:
When using the asset pipeline, paths to assets must be re-written and sass-rails provides -url and -path helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet.
image-url("rails.png") becomes url(/assets/rails.png)
image-path("rails.png") becomes "/assets/rails.png".
The more generic form can also be used but the asset path and class must both be specified:
asset-url("rails.png", image) becomes url(/assets/rails.png)
asset-path("rails.png", image) becomes "/assets/rails.png"
Referenced By: Rails Guide Asset Pipe Line
Heading: 2.2.1 and 2.2.2 respectively.