我不能将图像作为背景硬编码到 CSS 中,因为它们当然对于每个产品都是不同的。 最佳答案 在 View 中,您需要调用 asset_u-6ren">
gpt4 book ai didi

ruby-on-rails - 渲染局部图像并将其传递给对象时,如何将 Assets 中的图像显示为背景图像

转载 作者:行者123 更新时间:2023-12-04 15:02:05 26 4
gpt4 key购买 nike

在索引页上:

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

在我的产品卡片部分:

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

我不能将图像作为背景硬编码到 CSS 中,因为它们当然对于每个产品都是不同的。

最佳答案

在 View 中,您需要调用 asset_url(product) 以使 URL 正确呈现,指向已编译的 Assets 。

请在此处查看这些文档以了解如何以不同方式呈现 Assets :https://guides.rubyonrails.org/asset_pipeline.html#css-and-sass

尝试:

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

内联样式不是首选,如果我是你,我可能会尝试在 View 中呈现图像的实际图像标记,并使用 object-fit css 指令将其定位在 div 中,放置其他内容在其之上。这将使您避免 CSP 和样式标签的陷阱。

关于ruby-on-rails - 渲染局部图像并将其传递给对象时,如何将 Assets 中的图像显示为背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66799557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com