背景
在默认的 packs/application.js
文件中,您会收到以下注释
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
使用这些评论,我创建了以下 JavaScript 函数以包含 app/assets/images
中的所有内容
const images = require.context('../../assets/images', true)
const imagePath = (name) => images(name, true)
我可以像这样调用 image_pack_tag
助手:
<%= image_pack_tag 'media/images/logo.svg' %>
但是,我有一个 HTML 标记,我需要在其中添加背景。现在,它看起来像这样:
<section class="bg-cover" style="background-image: url(assets/img/covers/cover.jpg);">
问题
有没有办法让我从 image_pack_tag
中提取图像的路径,以便我可以这样做:
<section class="bg-cover" style="background-image: url(<%= image_pack_tag_url 'media/covers/cover.jpg' %>);">
最佳答案
使用 asset_pack_path
助手。在您的情况下,您想使用:
asset_pack_path 'media/covers/cover.jpg'
在背景属性中,变成:
<section class="bg-cover" style="background-image: url(<%= asset_pack_path 'media/covers/cover.jpg' %>);">
关于ruby-on-rails - 是否可以从 image_pack_tag 中获取图像的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049182/