问题
I'm having trouble getting images I'm uploading using carrierwave to show in the blog I'm working on.
Here's the view code:
<div class="entry-header">
<div class="entry-image" style="background: image-url(<%= image_tag @blog.image_url.to_s %>)"> </div>
<h1 class="entry-title"><%= @blog.title %></h1>
</div>
Currently it's displaying )">
where the image and title should be. I'm able to make that disappear by removing the =
in the image tag, but that also doesn't solve the problem.
Here's the blog model:
class Blog < ActiveRecord::Base
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true
mount_uploader :image, BlogImageUploader
end
And I haven't made any changes tot he generic carrierwave generated uploader, though I can post that too if it's helpful. Anyone have any ideas?
As requested, the rendered html:
<div class="entry-header">
<div class="entry-image" style="background: <img src=" uploads="" blog="" image="" 980190964="" gcentral.jpg"="" alt="Gcentral">"> </div>
<h1 class="entry-title">Grand central test</h1>
</div>
回答1:
Ah, I see what's going on now. When you use <%= image_tag(...) %>
, Rails generates a <img src="..." alt="..." foo="..." bar="..." />
tag that is used to display a regular image in a page. What you're going to want is to just output the image URL instead with
style="background: url(<%= @blog.image_url %>)"
This will print something like url(http://foo/bar/baz.jpg)
like you want. Note that I also changed image-url
to url
, as image-url
is something that you get to use under the /app/assets/stylesheets files, but isn't available in style attributes. Look up sprockets for more info if you're curious.
You probably also want to use some sanitization in there, because a crafty hacker could upload an image with a name like "><script>alert('hacked!')</script>
to execute scripts on your page.
来源:https://stackoverflow.com/questions/33248021/background-images-with-carreirwave