2

I want to get the absolute url of an image in my css as follows:

"#{request.scheme}://#{request.host_with_port}/assets/image.png);"

But I think request attributes cannot be accessed in css.erb. Can anyone tell me how else can I get the request scheme and host_with_port attributes in my css?

キキジキ
  • 1,443
  • 1
  • 25
  • 44
random
  • 10,238
  • 8
  • 57
  • 101

2 Answers2

1

You can define "scheme" (more correct: protocol), host and port by defining asset_host in your application configuration, though this definition will be used for all your asset paths.

Refering to the Rails API documentation on Asset Tag Helpers request informations can be used:

ActionController::Base.asset_host = Proc.new { |source, request|
      "#{request.protocol}#{request.host_with_port}"
}

If you need different values for different types of assets, you can define filter criteria, e.g.:

ActionController::Base.asset_host = Proc.new { |source|
 if source.starts_with?('/images')
   "http://images.example.com"
 else
   "http://assets.example.com"
 end
}
ulf_t
  • 380
  • 1
  • 9
  • Tried it by putting it inside environments/development.rb but couldn't get it working. – random Jan 07 '13 at 11:50
  • try this in your environments/development.rb: `config.action_controller.asset_host...` – ulf_t Jan 07 '13 at 17:27
  • Thanks for help. I'm accepting it as it solves the question asked. Urls were replaced properly, but unfortunately it didn't help solve my problem which I have raised in another question: http://stackoverflow.com/questions/14208403/rails-imgkit-issues-in-exporting-images-with-html-and-css – random Jan 08 '13 at 04:53
0

You can define css with absolute url for any background image or other assets. So you can generate it dynamically following this How to get absolute image paths in your css files using sass/scss.

CSS

body {
  background-image: image-url(background.png);
}

In your environment file change it with yours

config.action_controller.asset_host = "http://your.domain.com/"

Then your css will look something like that:

body {
  background-image: url(http://your.domain.com/assets/background.png);
}
Lalit Kumar Maurya
  • 5,475
  • 2
  • 35
  • 29