【问题标题】:How to set dynamic background image of a div ONLY if an image is present in the database仅当数据库中存在图像时如何设置 div 的动态背景图像
【发布时间】:2019-08-12 22:04:03
【问题描述】:

我正在尝试通过 index.html.erb 为多个 div 获取动态背景图像,并通过从我的数据库中提取背景 URL 的内联样式来实现这一点(使用carrierwave)。它现在看起来像这样:

 <div class="style-box col-8 ml-auto mr-auto" style="background: url(<%= place.photos.first.picture.url %>)">
      <h1><%= link_to place.name, place_path(place) %></h1>
      <i><%= place.address %></i>
      <br /><br />
      <p><%= place.description %></p>

我遇到的问题是,当创建一个新位置时,如果新位置的图像不存在(它不会在创建后立即出现),则视图无法创建完整的 html数据不完整的页面(即 place.photos 为零)。有没有一种方法,使用这种方法或类似的方法,只有在新地方的图像存在时才使背景图像覆盖默认样式框背景?通常我会使用 if 语句,但想不出一种方法让 if 语句使用 rails 更新 CSS。

【问题讨论】:

    标签: html css ruby-on-rails


    【解决方案1】:

    如果你想保持内联,你可以这样做:

    <div class="style-box col-8 ml-auto mr-auto"
        style="background: url(<%= place.photos.first&.picture.url || "/images/default.jpg" %>)">
        <h1><%= link_to place.name, place_path(place) %></h1>
        <i><%= place.address %></i>
        <br /><br />
        <p><%= place.description %></p>
    </div>
    

    这是使用 or 运算符 (||),它允许第一个值通过(如果存在),或者第二个作为默认值。此外,如果没有照片,&amp; 将防止页面出现错误。这与写作本质上是一样的:

    style="background: url(
        <% if place.photos.first&.picture&.url %>
            <%= place.photos.first&.picture&.url %>
        <% else %>
            /images/default.jpg
        <% end %>
    )">
    

    你也可以把它移到一个帮助方法中让你清理东西,比如:

    # in one of the app/helpers modules
    def picture_url_or_default(place, default_url = '/images/default.jpg')
        return default_url if place.photos.empty
        return default_url if place.photos.first.picture.nil?
        return default_url if place.photos.first.picture.url.nil?
    
        place.photos.first.picture.url
    end
    
    # in the view
    <div class="style-box col-8 ml-auto mr-auto"
        style="background: url(<%= picture_url_or_default(place))">
    
        ...
    

    【讨论】:

    • 谢谢!不知道如何使用 ||和 & 用于内联样式。写得很好。
    猜你喜欢
    • 1970-01-01
    • 2011-02-18
    • 2022-07-11
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多