Thymeleaf Url Expression in .CSS File

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 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.

How to add css files to Spring boot application (Thymeleaf) pagination

try to add additional / at start here before assets

<link href="/assets/css/font-awesome.min.css" rel="stylesheet">

Set CSS variables from model object in Thymeleaf

If you want to set CSS variables, you should use CSS inlining.

<style th:inline="css">
:root {
--primary-color: [(${brandingConfig?.themeConfig?.primaryColor} ?: '#633EA5')];
--secondary-color: [(${brandingConfig?.themeConfig?.secondaryColor} ?: '#E9E6ED')];
}
</style>

Normally the Thymeleaf processor only evaluates expressions in th:* attributes of tags. However, if you set th:inline="css" on your style tag you can use [[...]] expressions to evaluate the text inside a tag.

Changing .css files links via .properties files

Since Theme support is deprecated in Spring 6 I will use JavaScript as an easy workaround.

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.

Thymeleaf Template Resolves Model Attribute By Escaping Pound Sign In CSS file

I think Thymeleaf is trying to escape your CSS as a CSS identifier.

That being said, you can simply change your expressions from the escaped form /*[[${...}]]*/ to the unescaped form /*[(${...})]*/ and it won't escape your color codes.

.bgMainColor{
background-color: /*[(${styleProperties.Main_Color})]*/ pink;
}

Variable in a link

You can use string concatenation like this:

<link th:href="@{'/themes/'+${theme}+'/general/general.css'}" rel="stylesheet" />


Related Topics



Leave a reply



Submit