【问题标题】:Showing default image Thymleaf显示默认图像 Thymeleaf
【发布时间】:2021-05-24 17:07:45
【问题描述】:

当图像存在时,我想在 thymleaf 中显示背景图像,但如果不存在,我想在那里显示默认图像。我尝试的是下面

<div class="reward-header"
 th:attrappend="style='background-image:url('+ ${rewardCampaign.image != null ? 
 rewardCampaign.image : '' } + ')'  ">

在最后一个空引号中,我想放一个像这样的默认图像

<div class="reward-header"
 th:attrappend="style='background-image:url('+ ${rewardCampaign.image != null ? 
 rewardCampaign.image : @{/assets/img/samp-img-1.jpg} } + ')'  ">

但它显示错误。正确的语法是什么?

【问题讨论】:

  • 使用两个 div - 一个使用th:if,另一个使用th:unless - 在这里可能不那么麻烦(见仁见智)。各种SO题中都有例子,如this one;还有the documentation.

标签: thymeleaf


【解决方案1】:

试试下面的sn-p

<div class="reward-header" th:with="imageUrl=${rewardCampaign.image} ?  
   ${rewardCampaign.image } : @{'/assets/img/samp-img-1.jpg'}"  
    th:style="'background-image:url('+${imageUrl}+')'">

【讨论】:

    【解决方案2】:

    这样的事情怎么样?

    <div  th:with="image=${rewardCampaign.image} ?: @{/assets/img/samp-img-1.jpg}"
          th:style="|background-image: url('${image}')|"
          class="reward-header">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2012-01-27
      • 2015-11-16
      • 2013-02-02
      相关资源
      最近更新 更多