Heroku上的Rails 4有一个奇怪的问题。当图像被编译时,它们被添加了散列,但从CSS中引用这些文件时没有适当的名称调整。这就是我的意思。我有一个叫logo。png的文件。然而,当它出现在heroku上时,它被视为:

/assets/logo-200a00a193ed5e297bb09ddd96afb953.png

然而,CSS仍然声明:

background-image:url("./logo.png");

结果是:图像无法显示。有人遇到过这种情况吗?如何解决这个问题?


当前回答

当使用宝石'sass-rails'时,在Rails 5, bootstrap 4中,以下对我有用,

在.scss文件:

    background-image: url(asset_path("black_left_arrow.svg"));

视图文件(例如.html.slim):

    style=("background-image: url(#{ show_image_path("event_background.png") })");

其他回答

在Rails 4中,你可以像这样在你的.SCSS文件中引用位于assets/images/中的图像:

.some-div {
  background-image: url(image-path('pretty-background-image.jpg'));
}

当你以开发模式启动应用程序时(localhost:3000),你应该会看到如下内容:

background-image: url("/assets/pretty-background-image.jpg");

在生产模式下,你的资产将有缓存助手编号:

background-image: url("/assets/pretty-background-image-8b313354987c309e3cd76eabdb376c1e.jpg");

这应该能让你每次都做到。

background-image: url(<%= asset_data_uri 'transparent_2x2.png'%>);

在某些情况下,以下几点也适用

Logo {background: url(<%= asset_data_uri ' Logo .png' %>)}

来源:http://guides.rubyonrails.org/asset_pipeline.html

我摆弄了几个小时后发现:

工作原理:

background-image: url(image_path('transparent_2x2.png')); 

// how to add attributes like repeat, center, fixed?

上面的输出类似于:“/assets/transparent_2x2-ec47061dbe4fb88d51ae1e7f41a146db.png”

注意前面的“/”,它在引号内。 还要注意stylesheet.css.scss中的scss扩展和image_path帮助器。图片在app/assets/images目录下。

不工作:

background: url(image_path('transparent_2x2.png') repeat center center fixed;

无效属性:

background:url(/assets/pretty_photo/default/sprite.png) 2px 1px repeat center fixed;

我最后的办法是把这些放到我的公共s3桶里,然后从那里加载,但最后还是有了一些东西。

没有一个答案是关于。css的。Erb扩展,如何引用图像。对我来说,我同时从事生产和开发工作:

2.3.1 CSS和ERB

资产管道自动评估ERB。这意味着如果你添加一个erb扩展到一个CSS资产(例如,application.css.erb),那么像asset_path这样的助手在你的CSS规则中是可用的:

.class { background-image: url(<%= asset_path 'image.png' %>) }

这将写入被引用的特定资产的路径。在这个例子中,在一个资源加载路径中有一个图像是有意义的,比如app/assets/images/image.png,这里将引用它。如果此图像已作为指纹文件在公共/资产中可用,则会引用该路径。

如果您想使用数据URI(一种将图像数据直接嵌入到CSS文件中的方法),您可以使用asset_data_uri帮助器。

.logo { background: url(<%= asset_data_uri 'logo.png' %>) }

这将在CSS源中插入格式化正确的数据URI。

注意,结束标记的样式不能是-%>。