我的 Rails 应用程序中有一个 div
标记 (new.html.erb):
<div style="background: url(images/background.jpg) no-repeat;">
</div>
图像没有出现,我收到一个 ActionController
路由错误 No route matches [GET] "/locations/images/background.jpg"
问题是 Rails 将 locations/
添加到文件路径,这是错误的,因为我的图像正确位于 app/assets/images/background.jpg 中。
即使我包含文件的绝对路径,我也会将 locations
添加到它的开头。
这是我的路线(不确定是否有帮助,但不会造成伤害!):
locations GET /locations(.:format) locations#index
POST /locations(.:format) locations#create
new_location GET /locations/new(.:format) locations#new
edit_location GET /locations/:id/edit(.:format) locations#edit
location GET /locations/:id(.:format) locations#show
PATCH /locations/:id(.:format) locations#update
PUT /locations/:id(.:format) locations#update
DELETE /locations/:id(.:format) locations#destroy
最佳答案
您需要在 View 中使用 image_path
帮助程序生成 url:
<div style="background-image: url('<%= image_path('background.jpg') %>'); background-repeat: no-repeat">
</div>
助手很重要,因为在生产中您的 Assets 可能会被指纹识别或远程托管(例如在 CDN 上)。助手将始终生成正确的 url。
编辑:
要在 css 文件中引用背景图像,您有两种选择。使用 base rails,您可以将 .erb
添加到您的 css 文件名的末尾并使用上面的代码替换。
stylesheet.css.erb:
.myclass {
background-image: url(<%= asset_path 'background.png' %>);
}
或者,如果您使用的是 sass-rails
gem,您可以使用 image-url
或 asset-url
助手:
样式表.scss:
.myclass {
background-image: image-url('background.png'); // or asset-url('background.png');
}
参见 Asset Pipeline Guide获取更多信息。
关于html img 标签不起作用,因为生成了错误的路径 Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641817/