简体   繁体   中英

How can I show an image from assets as a background image when rendering a partial and passing it an object

On the index page:

<% @products.each do |prod| %>
  <%= render 'shared/product_card', product: prod %>
<% end %>

In my product card partial:

<div class="product-card-image" style='background-image: url("<%= product.name %>.jpeg")'></div>

I can't hard-code the images into the CSS as background since they are different for each product of course.

In the views you need to call asset_url(product) for the URL to render correctly, pointing to the compiled asset.

Please view these docs here to see how to render the assets in different ways:https://guides.rubyonrails.org/asset_pipeline.html#css-and-sass

Try:

<div class="product-card-image" style='background-image: url(<%= asset_path('product.png') %>)'></div>

Inline styles are not preferred, If I were you I might try to render the actual image tag for the image in the view, and position it in the div with object-fit css directives, placing other content on top of it. This will allow you to avoid the pitfalls of CSP and style tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM