ruby-on-rails - 是否可以从 image_pack_tag 中获取图像的 URL?

标签 ruby-on-rails webpacker

背景

在默认的 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/

相关文章:

javascript - rails : onchange posting not sending param

ruby-on-rails - 使用 RoR 从文本单元中抓取第一段?

ruby-on-rails - 如果库可用,则为 native C 扩展

ruby-on-rails - Ruby on Rails 路线说明

vue.js - 使用 Webpacker 从 Rails 5 中的子路径提供 Vue.js 应用程序

javascript - Vue JS 2 on Rails 5.1 'You may need an appropriate loader to handle this file type.'

ruby-on-rails - 如何在没有 tilda 的情况下从 node_modules 导入 scss 文件?

mysql - Rails - MySql 应用程序 - 报告和图表要求

ruby-on-rails - Rails 6 + Webpacker 4 + PostCSS和@ font-face +本地字体

webpacker - Bootstrap JS函数未在Rails 6/Webpacker中加载