使用Thymeleaf设置CSS样式属性

20

如何使用Thymeleaf解析URL并设置样式标签的背景属性。

我有

<div style="background:url('<url-to-image>')"></div>

是否有类似于在Thymeleaf中设置样式属性的<img th:src="${@/<path-to-image>}">等价物。

4个回答

51

如果您使用th:style设置样式属性,那么您可以实现这一点:

<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

请查看thymeleaf论坛上主题。


8
谢谢。有时语法确实很头疼。 - SpaceBeers
我怎样可以将变量从后端传递到width属性? - Shaaban Ebrahim
我在Spring Boot中遇到了以下异常:除非您实现org.thymeleaf.context.IWebContext接口(上下文为类:org.thymeleaf.context.Context),否则不能是上下文相对(/)或页面相对。 - Krish

9

@Leandro Carracedo建议的答案对我没有起作用(但在一定程度上有所帮助),我需要添加第二对括号和'$'符号才能从变量中获取值。

<td th:style="'font-size:'+@{${headerTemplateTextSize}}+'; -webkit-margin-before: 0.67em; -webkit-margin-after: 0.67em; -webkit-margin-start: 0px;-webkit-margin-end: 0px; font-weight: 300; max-width: 100px'">
    <div>...</div>
</td>

5

您还可以使用文字替换:

<div th:style="|background:url(@{/<path-to-image>});|"></div>

3

我希望这能对某些人有所帮助。

请确保您的图像大小小于屏幕像素大小。否则,无论是“background”还是“background-image”都无法正常工作。

Leandro的语法可以正常工作。也考虑使用这个(使用“background-image”而不是“background”)。

<div th:style="'background-image:url(' + @{/images/R1.jpg} + ');'">

这个属性会在图片过小的情况下拉伸图片,而不是重复显示图片(不需要声明“no-repeat”)。

1
完全不相关。请坚持主题并使用注释。 - Jelle Blaauw
@Jelle Blaauw - 你是个很酷的人。我仍然希望/相信它会对某些人有所帮助。 - Ula
谢谢兄弟,你帮了我很多!! - Rosyec Parrado

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接