简体   繁体   English

渲染部分图像并将其传递给 object 时,如何将资产中的图像显示为背景图像

[英]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.我不能将图像硬编码到 CSS 作为背景,因为它们对于每种产品当然是不同的。

In the views you need to call asset_url(product) for the URL to render correctly, pointing to the compiled asset.在视图中,您需要调用asset_url(product)才能正确呈现,指向已编译的资产。

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请在此处查看这些文档以了解如何以不同方式呈现资产: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.内联 styles 不是首选,如果我是你,我可能会尝试在视图中渲染图像的实际图像标签,并将 position 放在 div 中,并在 div 中使用object-fit ZC7A628CBA22E28EB17B5F5C6AE2A26AZ 指令放置其他内容。 This will allow you to avoid the pitfalls of CSP and style tags.这将允许您避免 CSP 和样式标签的陷阱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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