How to Set Background Url for CSS Files in Thymeleaf

How to set background url for css files in thymeleaf?

So, here's how to set dynamic relative paths in background image url property in the css using thymeleaf's inline text value,

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

which loads the image using relative path and we don't have to specific the 'myapp' context name in the url.

Thymeleaf URL expression in .css file

Put all your images folder structure with images path/to/image/bg.png inside the images folder under resources/static. Then refer to it in CSS as:

.background {
width: 100%;
background-image: url('../images/path/to/image/bg.png');
}

And then you can use this CSS in your templates as:

<head>
<link rel="stylesheet" media="screen" th:href="@{/css/application.css}"/>
</head>

Your files structure should look like this:

Sample Image

How to specify background image with Thymeleaf?

It probably needs to look like this:

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

But it depends on what dpurl contains. Do you really need to use @{...}? Then you should use @{${dpurl}}.

To debug this, you should be looking at the source. it will reveal what your expressions are resolving too.

Problem With Thymeleaf Background Image Url

Welcome to SO. When you ask a question, please try to provide as much information as possible about the issue, like the stack trace, the log, or the unexpected behaviour.

Meanwhile, try the following:

th:style="'background: url(/uploads/' + ${dashboard.dashboard_photo} + ');'"

HEX code color with thymeleaf for css inline

[[ ... ]] will escape what is there. Try [( .. )] instead:

--primary-color: [(${invoiceColor})];

See https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html chapter "Expression inlining":

Note that, while [[...]] corresponds to th:text (i.e. result will be HTML-escaped), [(...)] corresponds to th:utext and will not perform any HTML-escaping.



Related Topics



Leave a reply



Submit