【问题标题】:Insert div if background image exists如果存在背景图像,则插入 div
【发布时间】:2018-10-10 16:56:51
【问题描述】:

我有一个对象,它可能有也可能没有与之关联的图像。如果它确实有图像,我希望该图像用作 div 的背景图像。如果它没有图像,我不希望 div 显示。我正在使用 django 模板。到目前为止,这是我尝试过的:

{% if post.image %}
    <div class="background"></div>
{% endif %}

CSS 是:

.background{
  position: absolute;
  z-index: -1;
  background-image: url("{{ post.image.url }}");
  width: 100%;
  height: 400px;
}

图像存储在 AWS S3 中。发生的情况是,如果对象没有图像,则页面不会加载并告诉我“图像”属性没有与之关联的文件。我能做什么?

【问题讨论】:

    标签: html css django django-templates


    【解决方案1】:

    也为您的 css 添加验证并仅在图像存在时渲染图像:

    .background{
      position: absolute;
      z-index: -1;
      {% if post.image %}background-image: url("{{ post.image.url }}");{% endif %}
      width: 100%;
      height: 400px;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 2018-02-20
      • 1970-01-01
      • 2018-09-17
      相关资源
      最近更新 更多