在 rails 中使用资产管道的内联样式

Inline style using asset pipeline in rails

<%= link_to root_path do %>
    <div class="">
        <div style="background-image:<%= image_tag " image1.png "%>">
    </div>

    <div>
      <h2>Title</h2>
      <p>Paragraph</p>
    </div>
  </div>
<% end %>

我想从资产管道中提取图像作为我的背景。 我可以在 .sass 文件中完成。不过我每张都做了一个模板,觉得把每张照片都输入进去会更方便。

<div style="background-image:<%= image_tag "image1.png"%>"> 这是我确定语法的行。

替换 image_path 会给你一个 img 标签,为了给你 image1 文件的路径,试试 image_path:

<div style="background-image: <%= image_path 'image1' %>"></div>

如果您决定使用非内联样式,那么您也可以在 .scss 中使用 image-path

在html.erb

<div class="custom-background"></div>

在.scss

.custom-background {
 background-image: image-path('image1.png');
}

如果您使用 ERB 由资产管道解释,那么 asset_path 'image.png' 将 return 位于资产加载路径之一的图像的完整路径,您可以然后在url()里面使用。所以你的内联 div 可能看起来像:

<div style="background-image: url(<%= asset_path 'image1.png' %>)">

参考:CSS and ERB(注意 asset_path 助手中的 underscore (_)


如果您使用Sass,以下助手将帮助您使它更简洁:

  • image-url("rails.png") returns url(/assets/rails.png)
  • image-path("rails.png") returns "/assets/rails.png"

也可以使用更通用的形式:

  • asset-url("rails.png") returns url(/assets/rails.png)
  • asset-path("rails.png") returns "/assets/rails.png"

参考:CSS and Sass(注意上面的助手中的 dash (-)