如何在 thymeleaf 中为 css 文件设置背景 url?

How to set background url for css files in thymeleaf?

我有一个 thymeleaf 模板,其中我没有导入 CSS 文件,并且想用 background-image: url{/image.jpg} 属性 和相对图像 [=44] 声明 body 元素的样式属性=].我想加载 URL 而不包含应用程序上下文名称 (/myapp/)。它类似于 here 上的问题,只是它对我不起作用。

CSS:

<style>
body {
    background: url(../img/Background.jpg)
                no-repeat center center fixed;
    background-size: cover;
}
</style>

但是上面的 CSS 不起作用,它访问了

的图像
http://localhost/img/Background.jpg. 

因此,我必须将值设为 url(/myapp/img/Background.jpg) 才能正确加载图像。

我在 spring-context.xml 中正确设置了 mvc:resources 配置,以便 /img/ 请求正确加载并且它在其他地方工作。

spring-context.xml

<mvc:resources mapping="img/**" location="/WEB-INF/img/" />

那么如何使用 thymeleaf 的相对 url 动态加载背景 url 图像 css 值?

因此,这里是如何使用 thymeleaf 的内联文本值在 url 属性 中的背景图像 url 属性 中设置动态相对路径,

<style th:inline="text">
    body{
        background: url{[[@{/img/Background.jpg}]]}
                    no-repeat center center fixed;
    }
</style>

它使用相对路径加载图像,我们不必在 url.

中指定 'myapp' 上下文名称

就我而言,这有帮助: 将括号从卷曲改为圆形

<style th:inline="text">
body{
    background: url([[@{/img/Background.jpg}]])
                no-repeat center center fixed;
}
</style>

备选方案是:

<body th:style="'background: url(/img/la-paz-city.jpg) no-repeat center center fixed;'">
...
</body>

就这些了

    <body th:style="'background-image:url(' + @{/images/background.jpg} + '); background-repeat: no-repeat, repeat; background-size: cover;'">
    </body>