问题
I'm setting CSS color variables inside a style tag in a Thymeleaf template. The color values are coming from the model object. I also want to apply a default color, in case the model attirbute is not there.
But when I render the template, Thymeleaf doesn't evaluate the expression, but assigns the entire expression as a string literal, instead of the color value.
Below is my style tag. I've done the same thing in Apache Freemarker, and it worked fine. I'm pretty new to Thymeleaf, what should I do differently here?
<style>
:root {
--primary-color: ${brandingConfig?.themeConfig?.primaryColor} ?: '#633EA5';
--secondary-color: ${brandingConfig?.themeConfig?.secondaryColor} ?: '#E9E6ED';
}
</style>
回答1:
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.
来源:https://stackoverflow.com/questions/62610602/set-css-variables-from-model-object-in-thymeleaf