Set CSS variables from model object in Thymeleaf

橙三吉。 提交于 2021-02-11 12:17:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!