【问题标题】:How to specify background image with Thymeleaf?如何使用 Thymeleaf 指定背景图像?
【发布时间】:2018-07-16 15:50:19
【问题描述】:

我正在用百里香学习弹簧靴。我已将用户对象的个人资料图像存储在文件系统中,并且只有图像的 URL 是数据库中持久保存的用户对象的一部分。


我已添加 name 和 @987654322 @ 进入模型,以便从模板中访问它。

@GetMapping("/profile")
public String profileController(@AuthenticationPrincipal User activeUser, Model model) {
            model.addAttribute("name", activeUser.getName());
            model.addAttribute("dpurl", activeUser.getDpURL());
            return "profile";
        }

我可以使用th:text="${name}" 从模板访问name

但是,我无法像这样使用 thymeleaf 指定背景图片

<div id="dp-container" th:style="'background-image: url(' + @̣{dpurl} + ');'" >


这会导致错误
Could not parse as expression: "'background-image: url(' + @̣{dpurl} + ');'"



更新

改成这样了

<div id="dp-container"  th:style="'background-image:url(' + @{dpurl} + ');'">



现在我没有收到任何错误,但仍然没有显示背景图像。

如何使用 Thymeleaf 指定背景图像?

【问题讨论】:

  • #1 如果您想提高可读性,请使用 th:style="|background-image:url(@{dpurl});|"

标签: spring spring-boot thymeleaf


【解决方案1】:

它可能需要看起来像这样:

<div id="dp-container"  th:style="'background-image:url(' + ${dpurl} + ');'">

但这取决于dpurl 包含的内容。你真的需要使用@{...}吗?那么你应该使用@{${dpurl}}

要调试它,您应该查看源代码。它也会揭示你的表达式正在解决什么。

【讨论】:

  • dpurl 包含文件系统中图像的完全限定 url。是否可以从 webapp 访问这样的磁盘文件? ..我创建了一个简单的静态 html 页面,只有一个 &lt;img&gt; 元素,它的 src 属性包含光盘上图像的完全限定 url,它可以工作,但是当我将它移到 webapp 的 static 目录`时,图片没有显示?
  • 您将图像放在静态文件夹中,但您看不到图像。交付的 html-page 中生成的 style-attribute 是什么样的?
  • @Flocke 除图像外一切正常。我想问题是,图像位于不属于项目结构的目录中。无法托管网页访问本地文件中的文件项目目录之外的系统?
  • @Arjun:在本地,是的!您可以在同一机器上的浏览器中从本地(Windows)机器中打开每个文件,仅取决于访问权限。但是您不能将该图像提供给网络中的客户,因为他们的浏览器无权访问该文件。 ... Spring Boot 应该明确地将静态文件夹添加到路径中。因此,th:style"|background-image:url(${imgPath});|"如果 imgPath 类似于“/image/myImage.jpg”,则应该可以工作。我认为你在这里不需要@。
  • @Flocke 我完全忘记了,没有控制器的帮助,tomcat 和 spring boot 只能从它的 staticpublic 目录中提供静态内容...
【解决方案2】:

我得到了这个工作:

<td  th:style="'background: url(/images/aws2.png)'" class="fluid hero-image" >

【讨论】:

    【解决方案3】:

    好吧,如果你有更复杂的事情,比如需要将变量传递到 url,你可以试试这个:

    <div id="profile_image" th:style="'background-image: url('+ @{'/view-profile-pic/' + ${result.profile_pic}} +');'"></div>
    

    在 css 中,图像正确显示:

    #profile_image {
    margin: auto;
    height: 200px;
    width: 200px;
    box-sizing: border-box;
    border-radius: 100px;
    background-size: cover; 
    }
    

    当我想显示从搜索结果中收到的个人资料图片时,我偶然发现了这个解决方案。

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 2013-07-19
      • 2020-09-20
      • 2020-12-06
      • 2017-11-07
      • 2017-04-27
      • 1970-01-01
      • 2021-07-21
      • 2020-04-10
      相关资源
      最近更新 更多