How to set the background property of a style tag with a thymeleaf resolved url.
I have
<div style="background:url('<url-to-image>')"></div>
Is there a <img th:src="${@/<path-to-image>}">
equivalent for setting style attributes in thymeleaf.
Adding CSS. We load the stylesheet using the link tag with Thymeleaf's special th:href attribute. If we've used the expected directory structure, we only need to specify the path below src/main/resources/static. In this case, that's /styles/cssandjs/main.
In this tutorial, we learned how to call JavaScript functions in a Thymeleaf template. We started by setting up our dependencies. Then, we constructed our controller and template. Finally, we explored ways to call any JavaScript function inside Thymeleaf.
Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications.
An inline style may be used to apply a unique style for a single element. To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.
You could achieve that if you use th:style
to set your style attribute:
<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>
Check this thread on thymeleaf forum.
The answer suggested by @Leandro Carracedo did not work for me (but it helped along the way), I had to add second pair of brackets and '$' to get the value out of the variable
<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>
You can also use literal substitutions:
<div th:style="|background:url(@{/<path-to-image>});|"></div>
I hope it will help someone.
Please make sure that your image SIZE is SMALLER than screen size in pixels. Otherwise, neither 'background' nor 'background-image' did not work for me.
Leandro's syntax works fine. Consider using this one as well ( 'background-image' instead of 'background' )
<div th:style="'background-image:url(' + @{/images/R1.jpg} + ');'">
This one stretches out the image instead of repeating it if image is smaller ( no need to state 'no-repeat' )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With