【问题标题】:Rails 6/webpacker... how get background images to work BOTH in development and on Heroku?Rails 6/webpacker ...如何让背景图像在开发和 Heroku 上都可以工作?
【发布时间】:2021-06-25 11:59:44
【问题描述】:

在 Rails 6 应用程序中,我在 app/assets/images/bgs/abc.jpg 中有一个图像文件

要将该图像附加到body 背景,我怎样才能在application.html.haml 中的style 标记中有一个样式声明,它对both 都起作用same strong> 本地开发以及何时推送到 heroku?

在开发中工作,但不是 Heroku,因为我认为资产处理存在差异:

#application.html.haml
%style
  body::after {
  content: "";
  background: url("/assets/bgs/abc.jpg");  ### WORKS DEVT ONLY ###
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.12;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  background-attachment: fixed;
  z-index: -1;   
  }

我知道我应该使用asset_path,但这些在开发中都不起作用:

background: asset_path("/bgs/abc.jpg");
background: asset_path("bgs/abc.jpg");
background: asset_url("/bgs/abc.jpg");
background: asset_url("bgs/abc.jpg");

那里存在大量不一致的信息,有些情况说使用asset-url或asset-path,有些情况说asset_url或asset_path,甚至有些情况说use url(~filename.jpg),有些说use背景:有人说背景图像。

有没有一种简单的方法来使用背景图像,并且在开发和 Heroku 上都使用完全相同的代码?

【问题讨论】:

    标签: ruby-on-rails background-image asset-pipeline webpacker


    【解决方案1】:

    生产模式下的 Rails 将预编译资产,以便预编译资产文件夹(和子文件夹)上的所有图像并在公共文件夹上保存为 image name-fingeprint,例如:我有一个图像 assets/images/bgs/pragmatic_programmer.jpg,然后在运行命令后rake assets:precompile,这张图片会变成/public/assets/bgs/pragmatic_programmer-9aa8a13ac97f205fe891bee7c42c6e711f997186d8975d5a4106ca2fe53ccc61.jpg

    由于图像路径发生更改,您的应用程序在开发模式下工作而不是在生产模式下工作的原因,您可以通过ActionView::Helpers::AssetTagHelper#image_path 访问新编译的图像,如下所示

    #application.html.haml
    %style
      body::after {
      content: "";
      background: url(= image_path("bgs/abc.jpg"));
      ...
    }
    

    您可以在开发模式下进行测试,只需在启动服务器之前运行rake assets:precompile

    【讨论】:

      【解决方案2】:

      样式定义的答案是:

      背景:url(asset_path("bgs/abc.jpg"));

      适用于开发和生产。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 2021-05-20
        • 2013-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多