Setting CSS Style Attributes with Thymeleaf

Setting CSS style attributes with thymeleaf

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.

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.

Thymeleaf into style /style

You have to explicitly tell Thymeleaf to look for expressions in text with th:inline attribute, and than surround the expression with double square brackets.

<style th:inline="text">
paper-scroll-header-panel{
--paper-scroll-header-panel-full-header: {
background-image: url([[@{(${session.user.coverImagePath})}]]);
};
}
</style>

The authors of Thymeleaf have chosen this scheme for performance reasons, because the Thymeleaf's template parsing and processing is very different compared to JSP or Facelets.

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 - How to apply two (or more) styles based on mutually exclusive conditions

Thymeleaf has a th:styleappend attribute that allows for multiple styles to be applied:

<tr th:each="item, rowStat : ${items}" 
th:style="${rowStat.odd} ? 'background: #f0f0f2;' : 'background: #ffffff;'"
th:styleappend="${item.getValue()} > 5 ? 'color: red;' : 'color: black;'">

<td.... <!-- cols>

</tr>


Related Topics



Leave a reply



Submit