background images with carreirwave

╄→гoц情女王★ 提交于 2019-12-25 07:43:32

问题


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">"&gt; </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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!