I'd like for users to be able to upload images to use as their backgrounds on their profiles (users#show). Viewing source of some sites that have that fun开发者_如何学Goctionality (e.g. Twitter), it seems that users are assigned an html body tag and the corresponding CSS background-image for that body tag is linked to the image they have uploaded.
Any ideas of how I can do this? (Note: I am currently using paperclip for image upload, but will integrate that with an Amazon S3/similar service)
I thought about injecting a ruby instance variable to a CSS file/script from my users controller so that it would be dynamic, but I don't know if this is even possible. There's probably a better way.
I have implemented something similar in a project. I'll lay down the concept and give you a code example. I'll leave you to understand the logic or take bits of the code example to suit your kind of system implementation.
I would use a helper for this.
In app/views/layouts/application.html.erb
<head>
...
</head>
<body style="<%= show_user_bg %>">
...
</body>
In app/helpers/application_helper.rb
module ApplicationHelper
def show_user_bg
"background:transparent url(#{@user.background_image}) no-repeat fixed left top;"
end
end
Just make sure your user model has the background_image column and this is set.
Using a helper makes it more dynamic and cleaner. For example, you can throw in conditions:
module ApplicationHelper
def show_user_bg
# Show user background
if user_signed_in?
"background:transparent url(#{@user.background_image}) no-repeat fixed left top;"
# Otherwise, show a default background image
else
"background:transparent url('/images/default_bg.png') no-repeat fixed left top;"
end
end
end
Hope that helps!
Since it's data dependent, I would simply use an in-line style in the view.
Assuming the controller has loaded a model instance into @profile
that has a Paperclip attachment attribute called background_image
, ...
<body style="background-image:url(<%= @profile.background_image.url %>)">
...
</body>
There are various way to do this. I've seen the google search page. It added an image tag in the bottom of html body with absolute position to 0,0 and sets index as -2.
another way is to set the background image of body or your main div, you can do this using inline css attribute like
<body style="background-image: 'url(<%= user_image -%>)'">
where user_image is a helper method which calculates background image url for current user, this should handle the default image too i.e if user has not selected any image then it should return a default image probably a transparent image.
精彩评论