Adding an image_tag for the inline background-image url in Rails 5 template

余生颓废 提交于 2021-01-28 10:44:13

问题


I need to set the background image inline using the style tag, but it needs to reference an image object and not a fixed image from the assets folder. Below is my code to show what I am attempting to do.

<div class="background-image-holder" style="background: url(#{" image_path @product.photo_one_url(:original)"}); opacity: 1;">
  <%= image_tag(@product.photo_one_url(:medium)) %>
</div>

回答1:


I always prefer to use a content_tag if I'm including something dynamic like this, i.e.

<%= content_tag :div, class: "background-image-holder", 
                      style: { background: "url('#{image_path(@product.photo_one_url(:original))}')", 
                               opacity: 1 } do %>
...
<% end >

I feel it reads nicer than using inline erb tags - personal preference, but another option for you.



来源:https://stackoverflow.com/questions/47578595/adding-an-image-tag-for-the-inline-background-image-url-in-rails-5-template

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