Reputation: 10309
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?
Upvotes: 2
Views: 1746
Reputation: 5575
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);
}
Upvotes: 0
Reputation: 380
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
}
Upvotes: 1