简体   繁体   English

设置 CSS 变量从 model object 在 Z3982572505B879A8CF62684A803A0B5

[英]Set CSS variables from model object in Thymeleaf

I'm setting CSS color variables inside a style tag in a Thymeleaf template.我在 Thymeleaf 模板的样式标签内设置 CSS 颜色变量。 The color values are coming from the model object.颜色值来自 model object。 I also want to apply a default color, in case the model attirbute is not there.我还想应用默认颜色,以防 model 属性不存在。

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.但是当我渲染模板时, Thymeleaf 不会评估表达式,而是将整个表达式分配为字符串文字,而不是颜色值。

Below is my style tag.下面是我的风格标签。 I've done the same thing in Apache Freemarker, and it worked fine.我在 Apache Freemarker 中做过同样的事情,而且效果很好。 I'm pretty new to Thymeleaf, what should I do differently here?我对 Thymeleaf 很陌生,我应该在这里做些什么不同的事情?

<style>
  :root {
    --primary-color: ${brandingConfig?.themeConfig?.primaryColor} ?: '#633EA5';
    --secondary-color: ${brandingConfig?.themeConfig?.secondaryColor} ?: '#E9E6ED';
  }
</style>

If you want to set CSS variables, you should use CSS inlining .如果要设置 CSS 变量,则应使用CSS 内联

<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.通常 Thymeleaf 处理器只计算标签的th:*属性中的表达式。 However, if you set th:inline="css" on your style tag you can use [[...]] expressions to evaluate the text inside a tag.但是,如果您在样式标签上设置th:inline="css"您可以使用[[...]]表达式来评估标签内的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM