使用 Tailwind 从资产管道插入背景图像

Max*_*nce 7 ruby-on-rails asset-pipeline tailwind-css

我一直在尝试在我的项目中借助 Tailwind 添加背景图片,但它不起作用,我猜是因为某个地方的资产管道冲突?

我尝试过的:

  • tailwind.config像这样 直接将图像插入我的: 'essential-oil': "url('/assets/images/essential-oil.png')"'essential-oil': "asset-url('essential-oil.png')"
  • 使用 a 将图像直接插入到我的 HTML 中style: "background-image:url(/assets/images/essential-oil.png)
  • 将我的图像放在应用程序的其他位置,例如Public

所有解决方案都不起作用。最糟糕的是,我的所有样式最多都会从我的 HTML 中消失,样式看起来不错,但图片不存在。任何想法 ?

谢谢。

Ant*_*ans 5

您可以执行以下操作:

  1. 将图像移至 asset pipeline 目录下app/assets
  2. 参考tailwind.config.js中的新资源
module.exports = {
    theme: {
        extend: {
            backgroundImage: {
                'essential-oil': "url('essential-oil.png')"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 请参阅 HTML 中的背景图片
  <div class="bg-essential-oil">
  </div>
Run Code Online (Sandbox Code Playgroud)

细节

这是有效的,因为链轮已更改为支持指纹识别普通url([asset-path])引用。请参阅https://github.com/rails/sprockets-rails/pull/476。确保您使用的是 Sprockets 3.3.0 或更高版本。在存储库上打开问题后,我得到了答案tailwindcss-railshttps://github.com/rails/tailwindcss-rails/issues/137#issuecomment-1025853968

通过扩展,它还可以通过将 URL 内联来工作:

<div class="bg-[url('essential-oil.png')]">Has the essential oil background</div>
Run Code Online (Sandbox Code Playgroud)

参考

Rails 指南 - 资产管道


Tho*_*der 0

  1. 将图像移动到公用文件夹中
  2. 请参阅中的图像tailwind.config.js
module.exports = {

  theme: {
    extend: {
      backgroundImage: {
       'hero-pattern': "url('/assets/icon-arrows-left.svg')",
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)