【问题标题】:Fail to show CSS bg in Rails无法在 Rails 中显示 CSS bg
【发布时间】:2014-07-06 18:08:42
【问题描述】:

在我的应用程序的索引页面上工作,由于某种原因,我添加的 bg-image 没有呈现。但是我调用的所有其他图像文件都可以(但是在 CSS 中没有调用,就像这个一样)

它在开发中完美显示,但在生产中却没有。

我的 heroku 日志中出现以下错误:

ActionController::RoutingError (No route matches [GET] "/assets/ctabackground.png"):

我的 CSS:

#cta {
 text-align:center;
 height:600px;
 width:100%;
 background:url('ctabackground.png') no-repeat $light-green;
 h1, h2 {
 color:#fff;
}
 h2 {
  letter-spacing:2px;
  font-weight:300;
 }
}

文件位于 assets/images/ 作为 ctabackground.png

这里有什么问题?

【问题讨论】:

    标签: html css ruby-on-rails heroku


    【解决方案1】:

    您需要使用 rails asset_path 来获取正确的 url。试试:

    background-image: url(<%= asset_path 'ctabackground.png' %>) no-repeat $light-green;
    

    更新:

    由于您使用的是 sass,因此您可以使用 rails image-url helper

    background-image: image-url('ctabackground.png') no-repeat $light-green;
    

    【讨论】:

    • 是的,按照这些思路思考,唯一的问题是它在我的 .css.scss 文件中,因此它不运行 rails 代码。
    • @user2755537 哦,但是在生产中,rails 会预编译您的所有资产,并从内容中生成一个 MD5,因此您将无法访问像 assets/images/image.png 这样的路径,这就是我们使用asset_path 来制作正确网址的原因。如果您不想将其设为 erb 文件,那么我建议您使用 image_tag 而不是使用您的图像作为背景
    • 不知道!然后我学到了一些新东西 :) 仍然无法解决当前的问题。
    • @user2755537 你现在用得怎么样?并结帐guides.rubyonrails.org/asset_pipeline.html#in-production
    • 当我从我的 hmtl.erb 文件链接到图像时,我只是这样做
    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多