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

Viewed 110

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.

1 Answers

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.

Related