是否可以从 image_pack_tag 中获取图像的 URL?

Is it possible to get the URL of the image from the image_pack_tag?

背景

在默认 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' %>);">

对我来说,它只适用于 asset_pack_url:

method on github

asset_pack_url "static/some_image.webp" 关于您在 manifest.json

中的定义